com.vaadin.client.ui.VComboBox Maven / Gradle / Ivy
Show all versions of vaadin-client Show documentation
/*
* 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.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.JavaScriptObject;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
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.dom.client.Style.Visibility;
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.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
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.ComputedStyle;
import com.vaadin.client.DeferredWorker;
import com.vaadin.client.Focusable;
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.combobox.ComboBoxConnector;
import com.vaadin.client.ui.menubar.MenuBar;
import com.vaadin.client.ui.menubar.MenuItem;
import com.vaadin.shared.AbstractComponentState;
import com.vaadin.shared.ui.ComponentStateUtil;
import com.vaadin.shared.util.SharedUtil;
/**
* Client side implementation of the ComboBox component.
*
* TODO needs major refactoring (to be extensible etc)
*
* @since 8.0
*/
@SuppressWarnings("deprecation")
public class VComboBox extends Composite implements Field, KeyDownHandler,
KeyUpHandler, ClickHandler, FocusHandler, BlurHandler, Focusable,
SubPartAware, HandlesAriaCaption, HandlesAriaInvalid,
HandlesAriaRequired, DeferredWorker, MouseDownHandler {
/**
* Represents a suggestion in the suggestion popup box.
*/
public class ComboBoxSuggestion implements Suggestion, Command {
private final String key;
private final String caption;
private String untranslatedIconUri;
private String style;
/**
* Constructor for a single suggestion.
*
* @param key
* item key, empty string for a special null item not in
* container
* @param caption
* item caption
* @param style
* item style name, can be empty string
* @param untranslatedIconUri
* icon URI or null
*/
public ComboBoxSuggestion(String key, String caption, String style,
String untranslatedIconUri) {
this.key = key;
this.caption = caption;
this.style = style;
this.untranslatedIconUri = untranslatedIconUri;
}
/**
* 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();
ApplicationConnection client = connector.getConnection();
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("" + content + "");
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 real (translated) icon URI or null if none
*/
public String getIconUri() {
ApplicationConnection client = connector.getConnection();
return client.translateVaadinUri(untranslatedIconUri);
}
/**
* Gets the style set for this suggestion item. Styles are typically set
* by a server-side {@link com.vaadin.ui.ComboBox.ItemStyleProvider}.
* The returned style is prefixed by v-filterselect-item-
.
*
* @since 7.5.6
* @return the style name to use, or null
to not apply any
* custom style.
*/
public String getStyle() {
return style;
}
/**
* Executes a selection of this item.
*/
@Override
public void execute() {
onSuggestionSelected(this);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ComboBoxSuggestion)) {
return false;
}
ComboBoxSuggestion other = (ComboBoxSuggestion) 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;
}
if (!SharedUtil.equals(style, other.style)) {
return false;
}
return true;
}
}
/** An inner class that handles all logic related to mouse wheel. */
private class MouseWheeler extends JsniMousewheelHandler {
public MouseWheeler() {
super(VComboBox.this);
}
@Override
protected native JavaScriptObject createMousewheelListenerFunction(
Widget widget)
/*-{
return $entry(function(e) {
var deltaX = e.deltaX ? e.deltaX : -0.5*e.wheelDeltaX;
var deltaY = e.deltaY ? e.deltaY : -0.5*e.wheelDeltaY;
// IE8 has only delta y
if (isNaN(deltaY)) {
deltaY = -0.5*e.wheelDelta;
}
@com.vaadin.client.ui.VComboBox.JsniUtil::moveScrollFromEvent(*)(widget, deltaX, deltaY, e, e.deltaMode);
});
}-*/;
}
/**
* A utility class that contains utility methods that are usually called
* from JSNI.
*
* The methods are moved in this class to minimize the amount of JSNI code
* as much as feasible.
*/
static class JsniUtil {
private static final int DOM_DELTA_PIXEL = 0;
private static final int DOM_DELTA_LINE = 1;
private static final int DOM_DELTA_PAGE = 2;
// Rough estimation of item height
private static final int SCROLL_UNIT_PX = 25;
private static double deltaSum = 0;
public static void moveScrollFromEvent(final Widget widget,
final double deltaX, final double deltaY,
final NativeEvent event, final int deltaMode) {
if (!Double.isNaN(deltaY)) {
VComboBox filterSelect = (VComboBox) widget;
switch (deltaMode) {
case DOM_DELTA_LINE:
if (deltaY >= 0) {
filterSelect.suggestionPopup.selectNextItem();
} else {
filterSelect.suggestionPopup.selectPrevItem();
}
break;
case DOM_DELTA_PAGE:
if (deltaY >= 0) {
filterSelect.selectNextPage();
} else {
filterSelect.selectPrevPage();
}
break;
case DOM_DELTA_PIXEL:
default:
// Accumulate dampened deltas
deltaSum += Math.pow(Math.abs(deltaY), 0.7)
* Math.signum(deltaY);
// "Scroll" if change exceeds item height
while (Math.abs(deltaSum) >= SCROLL_UNIT_PX) {
if (!filterSelect.dataReceivedHandler
.isWaitingForFilteringResponse()) {
// Move selection if page flip is not in progress
if (deltaSum < 0) {
filterSelect.suggestionPopup.selectPrevItem();
} else {
filterSelect.suggestionPopup.selectNextItem();
}
}
deltaSum -= SCROLL_UNIT_PX * Math.signum(deltaSum);
}
break;
}
}
}
}
/**
* Represents the popup box with the selection options. Wraps a suggestion
* menu.
*/
public class SuggestionPopup extends VOverlay
implements PositionCallback, CloseHandler {
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;
private final MouseWheeler mouseWheeler = new MouseWheeler();
/**
* Default constructor
*/
SuggestionPopup() {
super(true, false);
debug("VComboBox.SP: constructor()");
setOwner(VComboBox.this);
menu = new SuggestionMenu();
setWidget(menu);
getElement().getStyle().setZIndex(Z_INDEX);
final Element root = getContainerElement();
up.setInnerHTML("Prev");
DOM.sinkEvents(up, Event.ONCLICK);
down.setInnerHTML("Next");
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);
}
@Override
protected void onLoad() {
super.onLoad();
// Register mousewheel listener on paged select
if (pageLength > 0) {
mouseWheeler.attachMousewheelListener(getElement());
}
}
@Override
protected void onUnload() {
mouseWheeler.detachMousewheelListener(getElement());
super.onUnload();
}
/**
* Shows the popup where the user can see the filtered options that have
* been set with a call to
* {@link SuggestionMenu#setSuggestions(Collection)}.
*
* @param currentPage
* The current page number
*/
public void showSuggestions(final int currentPage) {
debug("VComboBox.SP: showSuggestions(" + currentPage + ", "
+ getTotalSuggestions() + ")");
final SuggestionPopup popup = this;
// Add TT anchor point
getElement().setId("VAADIN_COMBOBOX_OPTIONLIST");
final int x = toInt32(WidgetUtil
.getBoundingClientRect(VComboBox.this.getElement())
.getLeft());
topPosition = toInt32(WidgetUtil
.getBoundingClientRect(tb.getElement()).getBottom())
+ Window.getScrollTop();
setPopupPosition(x, topPosition);
int nullOffset = getNullSelectionItemShouldBeVisible() ? 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 = getTotalSuggestions();
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 (getTotalSuggestionsIncludingNullSelectionItem() <= 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);
}
private native int toInt32(double val)
/*-{
return val | 0;
}-*/;
/**
* Should the next page button be visible to the user?
*
* @param active
*/
private void setNextButtonActive(boolean active) {
if (enableDebug) {
debug("VComboBox.SP: setNextButtonActive(" + active + ")");
}
if (active) {
DOM.sinkEvents(down, Event.ONCLICK);
down.setClassName(
VComboBox.this.getStylePrimaryName() + "-nextpage");
} else {
DOM.sinkEvents(down, 0);
down.setClassName(
VComboBox.this.getStylePrimaryName() + "-nextpage-off");
}
}
/**
* Should the previous page button be visible to the user
*
* @param active
*/
private void setPrevButtonActive(boolean active) {
if (enableDebug) {
debug("VComboBox.SP: setPrevButtonActive(" + active + ")");
}
if (active) {
DOM.sinkEvents(up, Event.ONCLICK);
up.setClassName(
VComboBox.this.getStylePrimaryName() + "-prevpage");
} else {
DOM.sinkEvents(up, 0);
up.setClassName(
VComboBox.this.getStylePrimaryName() + "-prevpage-off");
}
}
/**
* Selects the next item in the filtered selections.
*/
public void selectNextItem() {
debug("VComboBox.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("VComboBox.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("VComboBox.SP: selectFirstItem()");
selectItem(menu.getFirstItem());
}
/**
* Select the last item of the suggestions list popup.
*
* @since 7.2.6
*/
public void selectLastItem() {
debug("VComboBox.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.
ComboBoxSuggestion suggestion = (ComboBoxSuggestion) 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("VComboBox.SP.LPS: run()");
if (pagesToScroll != 0) {
if (!dataReceivedHandler.isWaitingForFilteringResponse()) {
/*
* 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.
*/
// this makes sure that we don't close the popup
dataReceivedHandler.setNavigationCallback(() -> {
});
filterOptions(currentPage + pagesToScroll, lastFilter);
}
pagesToScroll = 0;
}
}
public void scrollUp() {
debug("VComboBox.SP.LPS: scrollUp()");
if (pageLength > 0 && currentPage + pagesToScroll > 0) {
pagesToScroll--;
cancel();
schedule(200);
}
}
public void scrollDown() {
debug("VComboBox.SP.LPS: scrollDown()");
if (pageLength > 0
&& getTotalSuggestionsIncludingNullSelectionItem() > (currentPage
+ pagesToScroll + 1) * pageLength) {
pagesToScroll++;
cancel();
schedule(200);
}
}
}
private void scroll(double deltaY) {
boolean scrollActive = menu.isScrollActive();
debug("VComboBox.SP: scroll() scrollActive: " + scrollActive);
if (!scrollActive) {
if (deltaY > 0d) {
lazyPageScroller.scrollDown();
} else {
lazyPageScroller.scrollUp();
}
}
}
@Override
public void onBrowserEvent(Event event) {
debug("VComboBox.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();
}
}
/*
* 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("VComboBox.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("VComboBox.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);
}
// ignoring the parameter as in V7
offsetHeight = getOffsetHeight();
final int desiredHeight = offsetHeight;
final int desiredWidth = getMainWidth();
debug("VComboBox.SP: desired[" + desiredWidth + ", "
+ desiredHeight + "]");
Element menuFirstChild = menu.getElement().getFirstChildElement();
int naturalMenuWidth;
if (BrowserInfo.get().isIE()
&& BrowserInfo.get().getBrowserMajorVersion() < 10) {
// On IE 8 & 9 visibility is set to hidden and measuring
// elements while they are hidden yields incorrect results
String before = menu.getElement().getParentElement().getStyle()
.getVisibility();
menu.getElement().getParentElement().getStyle()
.setVisibility(Visibility.VISIBLE);
naturalMenuWidth = WidgetUtil.getRequiredWidth(menuFirstChild);
menu.getElement().getParentElement().getStyle()
.setProperty("visibility", before);
} else {
naturalMenuWidth = WidgetUtil.getRequiredWidth(menuFirstChild);
}
if (popupOuterPadding == -1) {
popupOuterPadding = WidgetUtil
.measureHorizontalPaddingAndBorder(menu.getElement(), 2)
+ WidgetUtil.measureHorizontalPaddingAndBorder(
suggestionPopup.getElement(), 0);
}
updateMenuWidth(desiredWidth, naturalMenuWidth);
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;
if (BrowserInfo.get().getBrowserMajorVersion() < 10) {
// On IE 8 & 9 visibility is set to hidden and measuring
// elements while they are hidden yields incorrect results
String before = menu.getElement().getParentElement()
.getStyle().getVisibility();
menu.getElement().getParentElement().getStyle()
.setVisibility(Visibility.VISIBLE);
naturalMenuOuterWidth = WidgetUtil
.getRequiredWidthDouble(menuFirstChild)
+ getMarginBorderPaddingWidth(menu.getElement());
menu.getElement().getParentElement().getStyle()
.setProperty("visibility", before);
} else {
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 textInputHeight = VComboBox.this.getOffsetHeight();
final int textInputTopOnPage = tb.getAbsoluteTop();
final int viewportOffset = Document.get().getScrollTop();
final int textInputTopInViewport = textInputTopOnPage
- viewportOffset;
final int textInputBottomInViewport = textInputTopInViewport
+ textInputHeight;
final int spaceAboveInViewport = textInputTopInViewport;
final int spaceBelowInViewport = Window.getClientHeight()
- textInputBottomInViewport;
if (spaceBelowInViewport < offsetHeight
&& spaceBelowInViewport < spaceAboveInViewport) {
// popup on top of input instead
if (offsetHeight > spaceAboveInViewport) {
// Shrink popup height to fit above
offsetHeight = spaceAboveInViewport;
}
top = textInputTopOnPage - offsetHeight;
} else {
// Show below, position calculated in showSuggestions for some
// strange reason
top = topPosition;
offsetHeight = Math.min(offsetHeight, spaceBelowInViewport);
}
// 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");
if (suggestionPopupWidth == null) {
final int naturalMenuWidthPlusScrollBar = naturalMenuWidth
+ WidgetUtil.getNativeScrollbarSize();
if (offsetWidth < naturalMenuWidthPlusScrollBar) {
menu.setWidth(naturalMenuWidthPlusScrollBar + "px");
}
}
}
if (offsetWidth + left > Window.getClientWidth()) {
left = VComboBox.this.getAbsoluteLeft()
+ VComboBox.this.getOffsetWidth() - offsetWidth;
if (left < 0) {
left = 0;
menu.setWidth(Window.getClientWidth() + "px");
}
}
setPopupPosition(left, top);
menu.scrollSelectionIntoView();
}
/**
* Adds in-line CSS rules to the DOM according to the
* suggestionPopupWidth field
*
* @param desiredWidth
* @param naturalMenuWidth
*/
private void updateMenuWidth(final int desiredWidth,
int naturalMenuWidth) {
/**
* Three different width modes for the suggestion pop-up:
*
* 1. Legacy "null"-mode: width is determined by the longest item
* caption for each page while still maintaining minimum width of
* (desiredWidth - popupOuterPadding)
*
* 2. relative to the component itself
*
* 3. fixed width
*/
String width = "auto";
if (suggestionPopupWidth == null) {
if (naturalMenuWidth < desiredWidth) {
naturalMenuWidth = desiredWidth - popupOuterPadding;
width = desiredWidth - popupOuterPadding + "px";
}
} else if (isrelativeUnits(suggestionPopupWidth)) {
float mainComponentWidth = desiredWidth - popupOuterPadding;
// convert percentage value to fraction
int widthInPx = Math.round(
mainComponentWidth * asFraction(suggestionPopupWidth));
width = widthInPx + "px";
} else {
// use as fixed width CSS definition
width = WidgetUtil.escapeAttribute(suggestionPopupWidth);
}
menu.setWidth(width);
}
/**
* Returns the percentage value as a fraction, e.g. 42% -> 0.42
*
* @param percentage
*/
private float asFraction(String percentage) {
String trimmed = percentage.trim();
String withoutPercentSign = trimmed.substring(0,
trimmed.length() - 1);
float asFraction = Float.parseFloat(withoutPercentSign) / 100;
return asFraction;
}
/**
* @since 7.7
* @param suggestionPopupWidth
* @return
*/
private boolean isrelativeUnits(String suggestionPopupWidth) {
return suggestionPopupWidth.trim().endsWith("%");
}
/**
* Was the popup just closed?
*
* @return true if popup was just closed
*/
public boolean isJustClosed() {
debug("VComboBox.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 event) {
if (enableDebug) {
debug("VComboBox.SP: onClose(" + event.isAutoClosed() + ")");
}
if (event.isAutoClosed()) {
lastAutoClosed = new Date().getTime();
}
}
/**
* Updates style names in suggestion popup to help theme building.
*
* @param componentState
* shared state of the combo box
*/
public void updateStyleNames(AbstractComponentState componentState) {
debug("VComboBox.SP: updateStyleNames()");
setStyleName(
VComboBox.this.getStylePrimaryName() + "-suggestpopup");
menu.setStyleName(
VComboBox.this.getStylePrimaryName() + "-suggestmenu");
status.setClassName(
VComboBox.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("VComboBox.SM: delayedImageLoadExecutioner()");
if (suggestionPopup.isVisible()
&& suggestionPopup.isAttached()) {
setWidth("");
getElement().getFirstChildElement().getStyle()
.clearWidth();
suggestionPopup
.setPopupPositionAndShow(suggestionPopup);
}
}
});
/**
* Default constructor
*/
SuggestionMenu() {
super(true);
debug("VComboBox.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 suggestions) {
if (enableDebug) {
debug("VComboBox.SM: setSuggestions(" + suggestions + ")");
}
clearItems();
final Iterator it = suggestions.iterator();
boolean isFirstIteration = true;
while (it.hasNext()) {
final ComboBoxSuggestion suggestion = it.next();
final MenuItem mi = new MenuItem(suggestion.getDisplayString(),
true, suggestion);
String style = suggestion.getStyle();
if (style != null) {
mi.addStyleName("v-filterselect-item-" + style);
}
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 && !allowNewItems) {
selectItem(mi);
}
if (currentSuggestion != null && suggestion.getOptionKey()
.equals(currentSuggestion.getOptionKey())) {
// Refresh also selected caption and icon in case they have
// been updated on the server, e.g. just the item has been
// updated, but selection (from state) has stayed the same.
// FIXME need to update selected item caption separately, if
// the selected item is not in "active data range" that is
// being sent to the client. Then this can be removed.
if (currentSuggestion.getReplacementString()
.equals(tb.getText())) {
currentSuggestion = suggestion;
selectItem(mi);
setSelectedCaption(
currentSuggestion.getReplacementString());
setSelectedItemIcon(currentSuggestion.getIconUri());
}
}
isFirstIteration = false;
}
}
/**
* Create/select a suggestion based on the used entered string. This
* method is called after filtering has completed with the given string.
*
* @param enteredItemValue
* user entered string
*/
public void actOnEnteredValueAfterFiltering(String enteredItemValue) {
debug("VComboBox.SM: doPostFilterSelectedItemAction()");
final MenuItem item = getSelectedItem();
// 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 ("".equals(enteredItemValue) && nullSelectionAllowed) {
onNullSelected();
} else if (allowNewItems) {
if (!enteredItemValue.equals(lastNewItemString)) {
// Store last sent new item string to avoid double sends
lastNewItemString = enteredItemValue;
connector.sendNewItem(enteredItemValue);
// TODO try to select the new value if it matches what was
// sent for V7 compatibility
}
} else if (item != null && !"".equals(lastFilter) && item.getText()
.toLowerCase().contains(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 {
onNullSelected();
}
}
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("VComboBox.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("VComboBox.SM: selectFirstItem()");
MenuItem firstItem = getItems().get(0);
selectItem(firstItem);
}
/**
* @deprecated use {@link SuggestionPopup#selectLastItem()} instead.
*/
@Deprecated
public void selectLastItem() {
debug("VComboBox.SM: selectLastItem()");
List