You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VComboBox.java 96KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Date;
  20. import java.util.HashSet;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Set;
  24. import com.google.gwt.aria.client.Roles;
  25. import com.google.gwt.core.client.JavaScriptObject;
  26. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  27. import com.google.gwt.dom.client.Document;
  28. import com.google.gwt.dom.client.Element;
  29. import com.google.gwt.dom.client.NativeEvent;
  30. import com.google.gwt.dom.client.Style;
  31. import com.google.gwt.dom.client.Style.Display;
  32. import com.google.gwt.dom.client.Style.Unit;
  33. import com.google.gwt.dom.client.Style.Visibility;
  34. import com.google.gwt.event.dom.client.BlurEvent;
  35. import com.google.gwt.event.dom.client.BlurHandler;
  36. import com.google.gwt.event.dom.client.ClickEvent;
  37. import com.google.gwt.event.dom.client.ClickHandler;
  38. import com.google.gwt.event.dom.client.FocusEvent;
  39. import com.google.gwt.event.dom.client.FocusHandler;
  40. import com.google.gwt.event.dom.client.KeyCodes;
  41. import com.google.gwt.event.dom.client.KeyDownEvent;
  42. import com.google.gwt.event.dom.client.KeyDownHandler;
  43. import com.google.gwt.event.dom.client.KeyUpEvent;
  44. import com.google.gwt.event.dom.client.KeyUpHandler;
  45. import com.google.gwt.event.dom.client.LoadEvent;
  46. import com.google.gwt.event.dom.client.LoadHandler;
  47. import com.google.gwt.event.dom.client.MouseDownEvent;
  48. import com.google.gwt.event.dom.client.MouseDownHandler;
  49. import com.google.gwt.event.logical.shared.CloseEvent;
  50. import com.google.gwt.event.logical.shared.CloseHandler;
  51. import com.google.gwt.i18n.client.HasDirection.Direction;
  52. import com.google.gwt.user.client.Command;
  53. import com.google.gwt.user.client.DOM;
  54. import com.google.gwt.user.client.Event;
  55. import com.google.gwt.user.client.Timer;
  56. import com.google.gwt.user.client.Window;
  57. import com.google.gwt.user.client.ui.Composite;
  58. import com.google.gwt.user.client.ui.FlowPanel;
  59. import com.google.gwt.user.client.ui.HTML;
  60. import com.google.gwt.user.client.ui.PopupPanel;
  61. import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
  62. import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
  63. import com.google.gwt.user.client.ui.TextBox;
  64. import com.google.gwt.user.client.ui.Widget;
  65. import com.vaadin.client.ApplicationConnection;
  66. import com.vaadin.client.BrowserInfo;
  67. import com.vaadin.client.ComputedStyle;
  68. import com.vaadin.client.DeferredWorker;
  69. import com.vaadin.client.Focusable;
  70. import com.vaadin.client.VConsole;
  71. import com.vaadin.client.WidgetUtil;
  72. import com.vaadin.client.ui.aria.AriaHelper;
  73. import com.vaadin.client.ui.aria.HandlesAriaCaption;
  74. import com.vaadin.client.ui.aria.HandlesAriaInvalid;
  75. import com.vaadin.client.ui.aria.HandlesAriaRequired;
  76. import com.vaadin.client.ui.combobox.ComboBoxConnector;
  77. import com.vaadin.client.ui.menubar.MenuBar;
  78. import com.vaadin.client.ui.menubar.MenuItem;
  79. import com.vaadin.shared.AbstractComponentState;
  80. import com.vaadin.shared.ui.ComponentStateUtil;
  81. import com.vaadin.shared.util.SharedUtil;
  82. /**
  83. * Client side implementation of the ComboBox component.
  84. *
  85. * TODO needs major refactoring (to be extensible etc)
  86. */
  87. @SuppressWarnings("deprecation")
  88. public class VComboBox extends Composite implements Field, KeyDownHandler,
  89. KeyUpHandler, ClickHandler, FocusHandler, BlurHandler, Focusable,
  90. SubPartAware, HandlesAriaCaption, HandlesAriaInvalid,
  91. HandlesAriaRequired, DeferredWorker, MouseDownHandler {
  92. /**
  93. * Represents a suggestion in the suggestion popup box.
  94. */
  95. public class ComboBoxSuggestion implements Suggestion, Command {
  96. private final String key;
  97. private final String caption;
  98. private String untranslatedIconUri;
  99. private String style;
  100. /**
  101. * Constructor for a single suggestion.
  102. *
  103. * @param key
  104. * item key, empty string for a special null item not in
  105. * container
  106. * @param caption
  107. * item caption
  108. * @param style
  109. * item style name, can be empty string
  110. * @param untranslatedIconUri
  111. * icon URI or null
  112. */
  113. public ComboBoxSuggestion(String key, String caption, String style,
  114. String untranslatedIconUri) {
  115. this.key = key;
  116. this.caption = caption;
  117. this.style = style;
  118. this.untranslatedIconUri = untranslatedIconUri;
  119. }
  120. /**
  121. * Gets the visible row in the popup as a HTML string. The string
  122. * contains an image tag with the rows icon (if an icon has been
  123. * specified) and the caption of the item
  124. */
  125. @Override
  126. public String getDisplayString() {
  127. final StringBuffer sb = new StringBuffer();
  128. ApplicationConnection client = connector.getConnection();
  129. final Icon icon = client
  130. .getIcon(client.translateVaadinUri(untranslatedIconUri));
  131. if (icon != null) {
  132. sb.append(icon.getElement().getString());
  133. }
  134. String content;
  135. if ("".equals(caption)) {
  136. // Ensure that empty options use the same height as other
  137. // options and are not collapsed (#7506)
  138. content = " ";
  139. } else {
  140. content = WidgetUtil.escapeHTML(caption);
  141. }
  142. sb.append("<span>" + content + "</span>");
  143. return sb.toString();
  144. }
  145. /**
  146. * Get a string that represents this item. This is used in the text box.
  147. */
  148. @Override
  149. public String getReplacementString() {
  150. return caption;
  151. }
  152. /**
  153. * Get the option key which represents the item on the server side.
  154. *
  155. * @return The key of the item
  156. */
  157. public String getOptionKey() {
  158. return key;
  159. }
  160. /**
  161. * Get the URI of the icon. Used when constructing the displayed option.
  162. *
  163. * @return real (translated) icon URI or null if none
  164. */
  165. public String getIconUri() {
  166. ApplicationConnection client = connector.getConnection();
  167. return client.translateVaadinUri(untranslatedIconUri);
  168. }
  169. /**
  170. * Gets the style set for this suggestion item. Styles are typically set
  171. * by a server-side {@link com.vaadin.ui.ComboBox.ItemStyleProvider}.
  172. * The returned style is prefixed by <code>v-filterselect-item-</code>.
  173. *
  174. * @since 7.5.6
  175. * @return the style name to use, or <code>null</code> to not apply any
  176. * custom style.
  177. */
  178. public String getStyle() {
  179. return style;
  180. }
  181. /**
  182. * Executes a selection of this item.
  183. */
  184. @Override
  185. public void execute() {
  186. onSuggestionSelected(this);
  187. }
  188. @Override
  189. public boolean equals(Object obj) {
  190. if (!(obj instanceof ComboBoxSuggestion)) {
  191. return false;
  192. }
  193. ComboBoxSuggestion other = (ComboBoxSuggestion) obj;
  194. if ((key == null && other.key != null)
  195. || (key != null && !key.equals(other.key))) {
  196. return false;
  197. }
  198. if ((caption == null && other.caption != null)
  199. || (caption != null && !caption.equals(other.caption))) {
  200. return false;
  201. }
  202. if (!SharedUtil.equals(untranslatedIconUri,
  203. other.untranslatedIconUri)) {
  204. return false;
  205. }
  206. if (!SharedUtil.equals(style, other.style)) {
  207. return false;
  208. }
  209. return true;
  210. }
  211. }
  212. /** An inner class that handles all logic related to mouse wheel. */
  213. private class MouseWheeler extends JsniMousewheelHandler {
  214. public MouseWheeler() {
  215. super(VComboBox.this);
  216. }
  217. @Override
  218. protected native JavaScriptObject createMousewheelListenerFunction(
  219. Widget widget)
  220. /*-{
  221. return $entry(function(e) {
  222. var deltaX = e.deltaX ? e.deltaX : -0.5*e.wheelDeltaX;
  223. var deltaY = e.deltaY ? e.deltaY : -0.5*e.wheelDeltaY;
  224. // IE8 has only delta y
  225. if (isNaN(deltaY)) {
  226. deltaY = -0.5*e.wheelDelta;
  227. }
  228. @com.vaadin.client.ui.VComboBox.JsniUtil::moveScrollFromEvent(*)(widget, deltaX, deltaY, e, e.deltaMode);
  229. });
  230. }-*/;
  231. }
  232. /**
  233. * A utility class that contains utility methods that are usually called
  234. * from JSNI.
  235. * <p>
  236. * The methods are moved in this class to minimize the amount of JSNI code
  237. * as much as feasible.
  238. */
  239. static class JsniUtil {
  240. private static final int DOM_DELTA_PIXEL = 0;
  241. private static final int DOM_DELTA_LINE = 1;
  242. private static final int DOM_DELTA_PAGE = 2;
  243. // Rough estimation of item height
  244. private static final int SCROLL_UNIT_PX = 25;
  245. private static double deltaSum = 0;
  246. public static void moveScrollFromEvent(final Widget widget,
  247. final double deltaX, final double deltaY,
  248. final NativeEvent event, final int deltaMode) {
  249. if (!Double.isNaN(deltaY)) {
  250. VComboBox filterSelect = (VComboBox) widget;
  251. switch (deltaMode) {
  252. case DOM_DELTA_LINE:
  253. if (deltaY >= 0) {
  254. filterSelect.suggestionPopup.selectNextItem();
  255. } else {
  256. filterSelect.suggestionPopup.selectPrevItem();
  257. }
  258. break;
  259. case DOM_DELTA_PAGE:
  260. if (deltaY >= 0) {
  261. filterSelect.selectNextPage();
  262. } else {
  263. filterSelect.selectPrevPage();
  264. }
  265. break;
  266. case DOM_DELTA_PIXEL:
  267. default:
  268. // Accumulate dampened deltas
  269. deltaSum += Math.pow(Math.abs(deltaY), 0.7)
  270. * Math.signum(deltaY);
  271. // "Scroll" if change exceeds item height
  272. while (Math.abs(deltaSum) >= SCROLL_UNIT_PX) {
  273. if (!filterSelect.dataReceivedHandler
  274. .isWaitingForFilteringResponse()) {
  275. // Move selection if page flip is not in progress
  276. if (deltaSum < 0) {
  277. filterSelect.suggestionPopup.selectPrevItem();
  278. } else {
  279. filterSelect.suggestionPopup.selectNextItem();
  280. }
  281. }
  282. deltaSum -= SCROLL_UNIT_PX * Math.signum(deltaSum);
  283. }
  284. break;
  285. }
  286. }
  287. }
  288. }
  289. /**
  290. * Represents the popup box with the selection options. Wraps a suggestion
  291. * menu.
  292. */
  293. public class SuggestionPopup extends VOverlay
  294. implements PositionCallback, CloseHandler<PopupPanel> {
  295. private static final int Z_INDEX = 30000;
  296. /** For internal use only. May be removed or replaced in the future. */
  297. public final SuggestionMenu menu;
  298. private final Element up = DOM.createDiv();
  299. private final Element down = DOM.createDiv();
  300. private final Element status = DOM.createDiv();
  301. private boolean isPagingEnabled = true;
  302. private long lastAutoClosed;
  303. private int popupOuterPadding = -1;
  304. private int topPosition;
  305. private final MouseWheeler mouseWheeler = new MouseWheeler();
  306. /**
  307. * Default constructor
  308. */
  309. SuggestionPopup() {
  310. super(true, false);
  311. debug("VComboBox.SP: constructor()");
  312. setOwner(VComboBox.this);
  313. menu = new SuggestionMenu();
  314. setWidget(menu);
  315. getElement().getStyle().setZIndex(Z_INDEX);
  316. final Element root = getContainerElement();
  317. up.setInnerHTML("<span>Prev</span>");
  318. DOM.sinkEvents(up, Event.ONCLICK);
  319. down.setInnerHTML("<span>Next</span>");
  320. DOM.sinkEvents(down, Event.ONCLICK);
  321. root.insertFirst(up);
  322. root.appendChild(down);
  323. root.appendChild(status);
  324. DOM.sinkEvents(root, Event.ONMOUSEDOWN | Event.ONMOUSEWHEEL);
  325. addCloseHandler(this);
  326. Roles.getListRole().set(getElement());
  327. setPreviewingAllNativeEvents(true);
  328. }
  329. @Override
  330. protected void onLoad() {
  331. super.onLoad();
  332. // Register mousewheel listener on paged select
  333. if (pageLength > 0) {
  334. mouseWheeler.attachMousewheelListener(getElement());
  335. }
  336. }
  337. @Override
  338. protected void onUnload() {
  339. mouseWheeler.detachMousewheelListener(getElement());
  340. super.onUnload();
  341. }
  342. /**
  343. * Shows the popup where the user can see the filtered options that have
  344. * been set with a call to
  345. * {@link SuggestionMenu#setSuggestions(Collection)}.
  346. *
  347. * @param currentPage
  348. * The current page number
  349. * @param totalSuggestions
  350. * The total amount of suggestions
  351. */
  352. public void showSuggestions(final int currentPage,
  353. final int totalSuggestions) {
  354. debug("VComboBox.SP: showSuggestions(" + currentPage + ", "
  355. + totalSuggestions + ")");
  356. final SuggestionPopup popup = this;
  357. // Add TT anchor point
  358. getElement().setId("VAADIN_COMBOBOX_OPTIONLIST");
  359. final int x = VComboBox.this.getAbsoluteLeft();
  360. topPosition = tb.getAbsoluteTop();
  361. topPosition += tb.getOffsetHeight();
  362. setPopupPosition(x, topPosition);
  363. int nullOffset = (nullSelectionAllowed && "".equals(lastFilter) ? 1
  364. : 0);
  365. boolean firstPage = (currentPage == 0);
  366. final int first = currentPage * pageLength + 1
  367. - (firstPage ? 0 : nullOffset);
  368. final int last = first + currentSuggestions.size() - 1
  369. - (firstPage && "".equals(lastFilter) ? nullOffset : 0);
  370. final int matches = totalSuggestions - nullOffset;
  371. if (last > 0) {
  372. // nullsel not counted, as requested by user
  373. status.setInnerText((matches == 0 ? 0 : first) + "-" + last
  374. + "/" + matches);
  375. } else {
  376. status.setInnerText("");
  377. }
  378. // We don't need to show arrows or statusbar if there is
  379. // only one page
  380. if (totalSuggestions <= pageLength || pageLength == 0) {
  381. setPagingEnabled(false);
  382. } else {
  383. setPagingEnabled(true);
  384. }
  385. setPrevButtonActive(first > 1);
  386. setNextButtonActive(last < matches);
  387. // clear previously fixed width
  388. menu.setWidth("");
  389. menu.getElement().getFirstChildElement().getStyle().clearWidth();
  390. setPopupPositionAndShow(popup);
  391. }
  392. /**
  393. * Should the next page button be visible to the user?
  394. *
  395. * @param active
  396. */
  397. private void setNextButtonActive(boolean active) {
  398. if (enableDebug) {
  399. debug("VComboBox.SP: setNextButtonActive(" + active + ")");
  400. }
  401. if (active) {
  402. DOM.sinkEvents(down, Event.ONCLICK);
  403. down.setClassName(
  404. VComboBox.this.getStylePrimaryName() + "-nextpage");
  405. } else {
  406. DOM.sinkEvents(down, 0);
  407. down.setClassName(
  408. VComboBox.this.getStylePrimaryName() + "-nextpage-off");
  409. }
  410. }
  411. /**
  412. * Should the previous page button be visible to the user
  413. *
  414. * @param active
  415. */
  416. private void setPrevButtonActive(boolean active) {
  417. if (enableDebug) {
  418. debug("VComboBox.SP: setPrevButtonActive(" + active + ")");
  419. }
  420. if (active) {
  421. DOM.sinkEvents(up, Event.ONCLICK);
  422. up.setClassName(
  423. VComboBox.this.getStylePrimaryName() + "-prevpage");
  424. } else {
  425. DOM.sinkEvents(up, 0);
  426. up.setClassName(
  427. VComboBox.this.getStylePrimaryName() + "-prevpage-off");
  428. }
  429. }
  430. /**
  431. * Selects the next item in the filtered selections.
  432. */
  433. public void selectNextItem() {
  434. debug("VComboBox.SP: selectNextItem()");
  435. final int index = menu.getSelectedIndex() + 1;
  436. if (menu.getItems().size() > index) {
  437. selectItem(menu.getItems().get(index));
  438. } else {
  439. selectNextPage();
  440. }
  441. }
  442. /**
  443. * Selects the previous item in the filtered selections.
  444. */
  445. public void selectPrevItem() {
  446. debug("VComboBox.SP: selectPrevItem()");
  447. final int index = menu.getSelectedIndex() - 1;
  448. if (index > -1) {
  449. selectItem(menu.getItems().get(index));
  450. } else if (index == -1) {
  451. selectPrevPage();
  452. } else {
  453. if (!menu.getItems().isEmpty()) {
  454. selectLastItem();
  455. }
  456. }
  457. }
  458. /**
  459. * Select the first item of the suggestions list popup.
  460. *
  461. * @since 7.2.6
  462. */
  463. public void selectFirstItem() {
  464. debug("VComboBox.SP: selectFirstItem()");
  465. selectItem(menu.getFirstItem());
  466. }
  467. /**
  468. * Select the last item of the suggestions list popup.
  469. *
  470. * @since 7.2.6
  471. */
  472. public void selectLastItem() {
  473. debug("VComboBox.SP: selectLastItem()");
  474. selectItem(menu.getLastItem());
  475. }
  476. /*
  477. * Sets the selected item in the popup menu.
  478. */
  479. private void selectItem(final MenuItem newSelectedItem) {
  480. menu.selectItem(newSelectedItem);
  481. // Set the icon.
  482. ComboBoxSuggestion suggestion = (ComboBoxSuggestion) newSelectedItem
  483. .getCommand();
  484. setSelectedItemIcon(suggestion.getIconUri());
  485. // Set the text.
  486. setText(suggestion.getReplacementString());
  487. }
  488. /*
  489. * Using a timer to scroll up or down the pages so when we receive lots
  490. * of consecutive mouse wheel events the pages does not flicker.
  491. */
  492. private LazyPageScroller lazyPageScroller = new LazyPageScroller();
  493. private class LazyPageScroller extends Timer {
  494. private int pagesToScroll = 0;
  495. @Override
  496. public void run() {
  497. debug("VComboBox.SP.LPS: run()");
  498. if (pagesToScroll != 0) {
  499. if (!dataReceivedHandler.isWaitingForFilteringResponse()) {
  500. /*
  501. * Avoid scrolling while we are waiting for a response
  502. * because otherwise the waiting flag will be reset in
  503. * the first response and the second response will be
  504. * ignored, causing an empty popup...
  505. *
  506. * As long as the scrolling delay is suitable
  507. * double/triple clicks will work by scrolling two or
  508. * three pages at a time and this should not be a
  509. * problem.
  510. */
  511. // this makes sure that we don't close the popup
  512. dataReceivedHandler.setNavigationCallback(() -> {
  513. });
  514. filterOptions(currentPage + pagesToScroll, lastFilter);
  515. }
  516. pagesToScroll = 0;
  517. }
  518. }
  519. public void scrollUp() {
  520. debug("VComboBox.SP.LPS: scrollUp()");
  521. if (pageLength > 0 && currentPage + pagesToScroll > 0) {
  522. pagesToScroll--;
  523. cancel();
  524. schedule(200);
  525. }
  526. }
  527. public void scrollDown() {
  528. debug("VComboBox.SP.LPS: scrollDown()");
  529. if (pageLength > 0
  530. && totalMatches > (currentPage + pagesToScroll + 1)
  531. * pageLength) {
  532. pagesToScroll++;
  533. cancel();
  534. schedule(200);
  535. }
  536. }
  537. }
  538. private void scroll(double deltaY) {
  539. boolean scrollActive = menu.isScrollActive();
  540. debug("VComboBox.SP: scroll() scrollActive: " + scrollActive);
  541. if (!scrollActive) {
  542. if (deltaY > 0d) {
  543. lazyPageScroller.scrollDown();
  544. } else {
  545. lazyPageScroller.scrollUp();
  546. }
  547. }
  548. }
  549. @Override
  550. public void onBrowserEvent(Event event) {
  551. debug("VComboBox.SP: onBrowserEvent()");
  552. if (event.getTypeInt() == Event.ONCLICK) {
  553. final Element target = DOM.eventGetTarget(event);
  554. if (target == up || target == DOM.getChild(up, 0)) {
  555. lazyPageScroller.scrollUp();
  556. } else if (target == down || target == DOM.getChild(down, 0)) {
  557. lazyPageScroller.scrollDown();
  558. }
  559. }
  560. /*
  561. * Prevent the keyboard focus from leaving the textfield by
  562. * preventing the default behaviour of the browser. Fixes #4285.
  563. */
  564. handleMouseDownEvent(event);
  565. }
  566. /**
  567. * Should paging be enabled. If paging is enabled then only a certain
  568. * amount of items are visible at a time and a scrollbar or buttons are
  569. * visible to change page. If paging is turned of then all options are
  570. * rendered into the popup menu.
  571. *
  572. * @param paging
  573. * Should the paging be turned on?
  574. */
  575. public void setPagingEnabled(boolean paging) {
  576. debug("VComboBox.SP: setPagingEnabled(" + paging + ")");
  577. if (isPagingEnabled == paging) {
  578. return;
  579. }
  580. if (paging) {
  581. down.getStyle().clearDisplay();
  582. up.getStyle().clearDisplay();
  583. status.getStyle().clearDisplay();
  584. } else {
  585. down.getStyle().setDisplay(Display.NONE);
  586. up.getStyle().setDisplay(Display.NONE);
  587. status.getStyle().setDisplay(Display.NONE);
  588. }
  589. isPagingEnabled = paging;
  590. }
  591. @Override
  592. public void setPosition(int offsetWidth, int offsetHeight) {
  593. debug("VComboBox.SP: setPosition(" + offsetWidth + ", "
  594. + offsetHeight + ")");
  595. int top = topPosition;
  596. int left = getPopupLeft();
  597. // reset menu size and retrieve its "natural" size
  598. menu.setHeight("");
  599. if (currentPage > 0 && !hasNextPage()) {
  600. // fix height to avoid height change when getting to last page
  601. menu.fixHeightTo(pageLength);
  602. }
  603. // ignoring the parameter as in V7
  604. offsetHeight = getOffsetHeight();
  605. final int desiredHeight = offsetHeight;
  606. final int desiredWidth = getMainWidth();
  607. debug("VComboBox.SP: desired[" + desiredWidth + ", "
  608. + desiredHeight + "]");
  609. Element menuFirstChild = menu.getElement().getFirstChildElement();
  610. int naturalMenuWidth;
  611. if (BrowserInfo.get().isIE()
  612. && BrowserInfo.get().getBrowserMajorVersion() < 10) {
  613. // On IE 8 & 9 visibility is set to hidden and measuring
  614. // elements while they are hidden yields incorrect results
  615. String before = menu.getElement().getParentElement().getStyle()
  616. .getVisibility();
  617. menu.getElement().getParentElement().getStyle()
  618. .setVisibility(Visibility.VISIBLE);
  619. naturalMenuWidth = WidgetUtil.getRequiredWidth(menuFirstChild);
  620. menu.getElement().getParentElement().getStyle()
  621. .setProperty("visibility", before);
  622. } else {
  623. naturalMenuWidth = WidgetUtil.getRequiredWidth(menuFirstChild);
  624. }
  625. if (popupOuterPadding == -1) {
  626. popupOuterPadding = WidgetUtil
  627. .measureHorizontalPaddingAndBorder(menu.getElement(), 2)
  628. + WidgetUtil.measureHorizontalPaddingAndBorder(
  629. suggestionPopup.getElement(), 0);
  630. }
  631. updateMenuWidth(desiredWidth, naturalMenuWidth);
  632. if (BrowserInfo.get().isIE()
  633. && BrowserInfo.get().getBrowserMajorVersion() < 11) {
  634. // Must take margin,border,padding manually into account for
  635. // menu element as we measure the element child and set width to
  636. // the element parent
  637. double naturalMenuOuterWidth;
  638. if (BrowserInfo.get().getBrowserMajorVersion() < 10) {
  639. // On IE 8 & 9 visibility is set to hidden and measuring
  640. // elements while they are hidden yields incorrect results
  641. String before = menu.getElement().getParentElement()
  642. .getStyle().getVisibility();
  643. menu.getElement().getParentElement().getStyle()
  644. .setVisibility(Visibility.VISIBLE);
  645. naturalMenuOuterWidth = WidgetUtil
  646. .getRequiredWidthDouble(menuFirstChild)
  647. + getMarginBorderPaddingWidth(menu.getElement());
  648. menu.getElement().getParentElement().getStyle()
  649. .setProperty("visibility", before);
  650. } else {
  651. naturalMenuOuterWidth = WidgetUtil
  652. .getRequiredWidthDouble(menuFirstChild)
  653. + getMarginBorderPaddingWidth(menu.getElement());
  654. }
  655. /*
  656. * IE requires us to specify the width for the container
  657. * element. Otherwise it will be 100% wide
  658. */
  659. double rootWidth = Math.max(desiredWidth - popupOuterPadding,
  660. naturalMenuOuterWidth);
  661. getContainerElement().getStyle().setWidth(rootWidth, Unit.PX);
  662. }
  663. final int textInputHeight = VComboBox.this.getOffsetHeight();
  664. final int textInputTopOnPage = tb.getAbsoluteTop();
  665. final int viewportOffset = Document.get().getScrollTop();
  666. final int textInputTopInViewport = textInputTopOnPage
  667. - viewportOffset;
  668. final int textInputBottomInViewport = textInputTopInViewport
  669. + textInputHeight;
  670. final int spaceAboveInViewport = textInputTopInViewport;
  671. final int spaceBelowInViewport = Window.getClientHeight()
  672. - textInputBottomInViewport;
  673. if (spaceBelowInViewport < offsetHeight
  674. && spaceBelowInViewport < spaceAboveInViewport) {
  675. // popup on top of input instead
  676. if (offsetHeight > spaceAboveInViewport) {
  677. // Shrink popup height to fit above
  678. offsetHeight = spaceAboveInViewport;
  679. }
  680. top = textInputTopOnPage - offsetHeight;
  681. } else {
  682. // Show below, position calculated in showSuggestions for some
  683. // strange reason
  684. top = topPosition;
  685. offsetHeight = Math.min(offsetHeight, spaceBelowInViewport);
  686. }
  687. // fetch real width (mac FF bugs here due GWT popups overflow:auto )
  688. offsetWidth = menuFirstChild.getOffsetWidth();
  689. if (offsetHeight < desiredHeight) {
  690. int menuHeight = offsetHeight;
  691. if (isPagingEnabled) {
  692. menuHeight -= up.getOffsetHeight() + down.getOffsetHeight()
  693. + status.getOffsetHeight();
  694. } else {
  695. final ComputedStyle s = new ComputedStyle(
  696. menu.getElement());
  697. menuHeight -= s.getIntProperty("marginBottom")
  698. + s.getIntProperty("marginTop");
  699. }
  700. // If the available page height is really tiny then this will be
  701. // negative and an exception will be thrown on setHeight.
  702. int menuElementHeight = menu.getItemOffsetHeight();
  703. if (menuHeight < menuElementHeight) {
  704. menuHeight = menuElementHeight;
  705. }
  706. menu.setHeight(menuHeight + "px");
  707. if (suggestionPopupWidth == null) {
  708. final int naturalMenuWidthPlusScrollBar = naturalMenuWidth
  709. + WidgetUtil.getNativeScrollbarSize();
  710. if (offsetWidth < naturalMenuWidthPlusScrollBar) {
  711. menu.setWidth(naturalMenuWidthPlusScrollBar + "px");
  712. }
  713. }
  714. }
  715. if (offsetWidth + left > Window.getClientWidth()) {
  716. left = VComboBox.this.getAbsoluteLeft()
  717. + VComboBox.this.getOffsetWidth() - offsetWidth;
  718. if (left < 0) {
  719. left = 0;
  720. menu.setWidth(Window.getClientWidth() + "px");
  721. }
  722. }
  723. setPopupPosition(left, top);
  724. menu.scrollSelectionIntoView();
  725. }
  726. /**
  727. * Adds in-line CSS rules to the DOM according to the
  728. * suggestionPopupWidth field
  729. *
  730. * @param desiredWidth
  731. * @param naturalMenuWidth
  732. */
  733. private void updateMenuWidth(final int desiredWidth,
  734. int naturalMenuWidth) {
  735. /**
  736. * Three different width modes for the suggestion pop-up:
  737. *
  738. * 1. Legacy "null"-mode: width is determined by the longest item
  739. * caption for each page while still maintaining minimum width of
  740. * (desiredWidth - popupOuterPadding)
  741. *
  742. * 2. relative to the component itself
  743. *
  744. * 3. fixed width
  745. */
  746. String width = "auto";
  747. if (suggestionPopupWidth == null) {
  748. if (naturalMenuWidth < desiredWidth) {
  749. naturalMenuWidth = desiredWidth - popupOuterPadding;
  750. width = (desiredWidth - popupOuterPadding) + "px";
  751. }
  752. } else if (isrelativeUnits(suggestionPopupWidth)) {
  753. float mainComponentWidth = desiredWidth - popupOuterPadding;
  754. // convert percentage value to fraction
  755. int widthInPx = Math.round(
  756. mainComponentWidth * asFraction(suggestionPopupWidth));
  757. width = widthInPx + "px";
  758. } else {
  759. // use as fixed width CSS definition
  760. width = WidgetUtil.escapeAttribute(suggestionPopupWidth);
  761. }
  762. menu.setWidth(width);
  763. }
  764. /**
  765. * Returns the percentage value as a fraction, e.g. 42% -> 0.42
  766. *
  767. * @param percentage
  768. */
  769. private float asFraction(String percentage) {
  770. String trimmed = percentage.trim();
  771. String withoutPercentSign = trimmed.substring(0,
  772. trimmed.length() - 1);
  773. float asFraction = Float.parseFloat(withoutPercentSign) / 100;
  774. return asFraction;
  775. }
  776. /**
  777. * @since 7.7
  778. * @param suggestionPopupWidth
  779. * @return
  780. */
  781. private boolean isrelativeUnits(String suggestionPopupWidth) {
  782. return suggestionPopupWidth.trim().endsWith("%");
  783. }
  784. /**
  785. * Was the popup just closed?
  786. *
  787. * @return true if popup was just closed
  788. */
  789. public boolean isJustClosed() {
  790. debug("VComboBox.SP: justClosed()");
  791. final long now = (new Date()).getTime();
  792. return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200);
  793. }
  794. /*
  795. * (non-Javadoc)
  796. *
  797. * @see
  798. * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google
  799. * .gwt.event.logical.shared.CloseEvent)
  800. */
  801. @Override
  802. public void onClose(CloseEvent<PopupPanel> event) {
  803. if (enableDebug) {
  804. debug("VComboBox.SP: onClose(" + event.isAutoClosed() + ")");
  805. }
  806. if (event.isAutoClosed()) {
  807. lastAutoClosed = (new Date()).getTime();
  808. }
  809. }
  810. /**
  811. * Updates style names in suggestion popup to help theme building.
  812. *
  813. * @param componentState
  814. * shared state of the combo box
  815. */
  816. public void updateStyleNames(AbstractComponentState componentState) {
  817. debug("VComboBox.SP: updateStyleNames()");
  818. setStyleName(
  819. VComboBox.this.getStylePrimaryName() + "-suggestpopup");
  820. menu.setStyleName(
  821. VComboBox.this.getStylePrimaryName() + "-suggestmenu");
  822. status.setClassName(
  823. VComboBox.this.getStylePrimaryName() + "-status");
  824. if (ComponentStateUtil.hasStyles(componentState)) {
  825. for (String style : componentState.styles) {
  826. if (!"".equals(style)) {
  827. addStyleDependentName(style);
  828. }
  829. }
  830. }
  831. }
  832. }
  833. /**
  834. * The menu where the suggestions are rendered
  835. */
  836. public class SuggestionMenu extends MenuBar
  837. implements SubPartAware, LoadHandler {
  838. private VLazyExecutor delayedImageLoadExecutioner = new VLazyExecutor(
  839. 100, new ScheduledCommand() {
  840. @Override
  841. public void execute() {
  842. debug("VComboBox.SM: delayedImageLoadExecutioner()");
  843. if (suggestionPopup.isVisible()
  844. && suggestionPopup.isAttached()) {
  845. setWidth("");
  846. getElement().getFirstChildElement().getStyle()
  847. .clearWidth();
  848. suggestionPopup
  849. .setPopupPositionAndShow(suggestionPopup);
  850. }
  851. }
  852. });
  853. /**
  854. * Default constructor
  855. */
  856. SuggestionMenu() {
  857. super(true);
  858. debug("VComboBox.SM: constructor()");
  859. addDomHandler(this, LoadEvent.getType());
  860. setScrollEnabled(true);
  861. }
  862. /**
  863. * Fixes menus height to use same space as full page would use. Needed
  864. * to avoid height changes when quickly "scrolling" to last page.
  865. */
  866. public void fixHeightTo(int pageItemsCount) {
  867. setHeight(getPreferredHeight(pageItemsCount));
  868. }
  869. /*
  870. * Gets the preferred height of the menu including pageItemsCount items.
  871. */
  872. String getPreferredHeight(int pageItemsCount) {
  873. if (currentSuggestions.size() > 0) {
  874. final int pixels = (getPreferredHeight()
  875. / currentSuggestions.size()) * pageItemsCount;
  876. return pixels + "px";
  877. } else {
  878. return "";
  879. }
  880. }
  881. /**
  882. * Sets the suggestions rendered in the menu.
  883. *
  884. * @param suggestions
  885. * The suggestions to be rendered in the menu
  886. */
  887. public void setSuggestions(Collection<ComboBoxSuggestion> suggestions) {
  888. if (enableDebug) {
  889. debug("VComboBox.SM: setSuggestions(" + suggestions + ")");
  890. }
  891. clearItems();
  892. final Iterator<ComboBoxSuggestion> it = suggestions.iterator();
  893. boolean isFirstIteration = true;
  894. while (it.hasNext()) {
  895. final ComboBoxSuggestion s = it.next();
  896. final MenuItem mi = new MenuItem(s.getDisplayString(), true, s);
  897. String style = s.getStyle();
  898. if (style != null) {
  899. mi.addStyleName("v-filterselect-item-" + style);
  900. }
  901. Roles.getListitemRole().set(mi.getElement());
  902. WidgetUtil.sinkOnloadForImages(mi.getElement());
  903. this.addItem(mi);
  904. // By default, first item on the list is always highlighted,
  905. // unless adding new items is allowed.
  906. if (isFirstIteration && !allowNewItems) {
  907. selectItem(mi);
  908. }
  909. if (currentSuggestion != null && s.getOptionKey()
  910. .equals(currentSuggestion.getOptionKey())) {
  911. // refresh also selected caption and icon in case they have
  912. // been updated on the server
  913. if (currentSuggestion.getReplacementString()
  914. .equals(tb.getText())) {
  915. currentSuggestion = s;
  916. selectItem(mi);
  917. setSelectedCaption(
  918. currentSuggestion.getReplacementString());
  919. setSelectedItemIcon(currentSuggestion.getIconUri());
  920. }
  921. }
  922. isFirstIteration = false;
  923. }
  924. }
  925. /**
  926. * Create/select a suggestion based on the used entered string. This
  927. * method is called after filtering has completed with the given string.
  928. *
  929. * @param enteredItemValue
  930. * user entered string
  931. */
  932. public void actOnEnteredValueAfterFiltering(String enteredItemValue) {
  933. debug("VComboBox.SM: doPostFilterSelectedItemAction()");
  934. final MenuItem item = getSelectedItem();
  935. // check for exact match in menu
  936. int p = getItems().size();
  937. if (p > 0) {
  938. for (int i = 0; i < p; i++) {
  939. final MenuItem potentialExactMatch = getItems().get(i);
  940. if (potentialExactMatch.getText()
  941. .equals(enteredItemValue)) {
  942. selectItem(potentialExactMatch);
  943. // do not send a value change event if null was and
  944. // stays selected
  945. if (!"".equals(enteredItemValue)
  946. || (selectedOptionKey != null
  947. && !"".equals(selectedOptionKey))) {
  948. doItemAction(potentialExactMatch, true);
  949. }
  950. suggestionPopup.hide();
  951. return;
  952. }
  953. }
  954. }
  955. if ("".equals(enteredItemValue) && nullSelectionAllowed) {
  956. onNullSelected();
  957. } else if (allowNewItems) {
  958. if (!enteredItemValue.equals(lastNewItemString)) {
  959. // Store last sent new item string to avoid double sends
  960. lastNewItemString = enteredItemValue;
  961. connector.sendNewItem(enteredItemValue);
  962. // TODO try to select the new value if it matches what was
  963. // sent for V7 compatibility
  964. }
  965. } else if (item != null && !"".equals(lastFilter) && (item.getText()
  966. .toLowerCase().contains(lastFilter.toLowerCase()))) {
  967. doItemAction(item, true);
  968. } else {
  969. // currentSuggestion has key="" for nullselection
  970. if (currentSuggestion != null
  971. && !currentSuggestion.key.equals("")) {
  972. // An item (not null) selected
  973. String text = currentSuggestion.getReplacementString();
  974. setText(text);
  975. selectedOptionKey = currentSuggestion.key;
  976. } else {
  977. onNullSelected();
  978. }
  979. }
  980. suggestionPopup.hide();
  981. }
  982. private static final String SUBPART_PREFIX = "item";
  983. @Override
  984. public com.google.gwt.user.client.Element getSubPartElement(
  985. String subPart) {
  986. int index = Integer
  987. .parseInt(subPart.substring(SUBPART_PREFIX.length()));
  988. MenuItem item = getItems().get(index);
  989. return item.getElement();
  990. }
  991. @Override
  992. public String getSubPartName(
  993. com.google.gwt.user.client.Element subElement) {
  994. if (!getElement().isOrHasChild(subElement)) {
  995. return null;
  996. }
  997. Element menuItemRoot = subElement;
  998. while (menuItemRoot != null
  999. && !menuItemRoot.getTagName().equalsIgnoreCase("td")) {
  1000. menuItemRoot = menuItemRoot.getParentElement().cast();
  1001. }
  1002. // "menuItemRoot" is now the root of the menu item
  1003. final int itemCount = getItems().size();
  1004. for (int i = 0; i < itemCount; i++) {
  1005. if (getItems().get(i).getElement() == menuItemRoot) {
  1006. String name = SUBPART_PREFIX + i;
  1007. return name;
  1008. }
  1009. }
  1010. return null;
  1011. }
  1012. @Override
  1013. public void onLoad(LoadEvent event) {
  1014. debug("VComboBox.SM: onLoad()");
  1015. // Handle icon onload events to ensure shadow is resized
  1016. // correctly
  1017. delayedImageLoadExecutioner.trigger();
  1018. }
  1019. /**
  1020. * @deprecated use {@link SuggestionPopup#selectFirstItem()} instead.
  1021. */
  1022. @Deprecated
  1023. public void selectFirstItem() {
  1024. debug("VComboBox.SM: selectFirstItem()");
  1025. MenuItem firstItem = getItems().get(0);
  1026. selectItem(firstItem);
  1027. }
  1028. /**
  1029. * @deprecated use {@link SuggestionPopup#selectLastItem()} instead.
  1030. */
  1031. @Deprecated
  1032. public void selectLastItem() {
  1033. debug("VComboBox.SM: selectLastItem()");
  1034. List<MenuItem> items = getItems();
  1035. MenuItem lastItem = items.get(items.size() - 1);
  1036. selectItem(lastItem);
  1037. }
  1038. /*
  1039. * Gets the height of one menu item.
  1040. */
  1041. int getItemOffsetHeight() {
  1042. List<MenuItem> items = getItems();
  1043. return items != null && items.size() > 0
  1044. ? items.get(0).getOffsetHeight() : 0;
  1045. }
  1046. /*
  1047. * Gets the width of one menu item.
  1048. */
  1049. int getItemOffsetWidth() {
  1050. List<MenuItem> items = getItems();
  1051. return items != null && items.size() > 0
  1052. ? items.get(0).getOffsetWidth() : 0;
  1053. }
  1054. /**
  1055. * Returns true if the scroll is active on the menu element or if the
  1056. * menu currently displays the last page with less items then the
  1057. * maximum visibility (in which case the scroll is not active, but the
  1058. * scroll is active for any other page in general).
  1059. *
  1060. * @since 7.2.6
  1061. */
  1062. @Override
  1063. public boolean isScrollActive() {
  1064. String height = getElement().getStyle().getHeight();
  1065. String preferredHeight = getPreferredHeight(pageLength);
  1066. return !(height == null || height.length() == 0
  1067. || height.equals(preferredHeight));
  1068. }
  1069. /**
  1070. * Highlight (select) an item matching the current text box content
  1071. * without triggering its action.
  1072. */
  1073. public void highlightSelectedItem() {
  1074. int p = getItems().size();
  1075. // first check if there is a key match to handle items with
  1076. // identical captions
  1077. String currentKey = currentSuggestion != null
  1078. ? currentSuggestion.getOptionKey() : "";
  1079. for (int i = 0; i < p; i++) {
  1080. final MenuItem potentialExactMatch = getItems().get(i);
  1081. if (currentKey.equals(getSuggestionKey(potentialExactMatch))
  1082. && tb.getText().equals(potentialExactMatch.getText())) {
  1083. selectItem(potentialExactMatch);
  1084. tb.setSelectionRange(tb.getText().length(), 0);
  1085. return;
  1086. }
  1087. }
  1088. // then check for exact string match in menu
  1089. String text = tb.getText();
  1090. for (int i = 0; i < p; i++) {
  1091. final MenuItem potentialExactMatch = getItems().get(i);
  1092. if (potentialExactMatch.getText().equals(text)) {
  1093. selectItem(potentialExactMatch);
  1094. tb.setSelectionRange(tb.getText().length(), 0);
  1095. return;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. private String getSuggestionKey(MenuItem item) {
  1101. if (item != null && item.getCommand() != null) {
  1102. return ((ComboBoxSuggestion) item.getCommand()).getOptionKey();
  1103. }
  1104. return "";
  1105. }
  1106. /**
  1107. * TextBox variant used as input element for filter selects, which prevents
  1108. * selecting text when disabled.
  1109. *
  1110. * @since 7.1.5
  1111. */
  1112. public class FilterSelectTextBox extends TextBox {
  1113. /**
  1114. * Creates a new filter select text box.
  1115. *
  1116. * @since 7.6.4
  1117. */
  1118. public FilterSelectTextBox() {
  1119. /*-
  1120. * Stop the browser from showing its own suggestion popup.
  1121. *
  1122. * Using an invalid value instead of "off" as suggested by
  1123. * https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
  1124. *
  1125. * Leaving the non-standard Safari options autocapitalize and
  1126. * autocorrect untouched since those do not interfere in the same
  1127. * way, and they might be useful in a combo box where new items are
  1128. * allowed.
  1129. */
  1130. getElement().setAttribute("autocomplete", "nope");
  1131. }
  1132. /**
  1133. * Overridden to avoid selecting text when text input is disabled
  1134. */
  1135. @Override
  1136. public void setSelectionRange(int pos, int length) {
  1137. if (textInputEnabled) {
  1138. /*
  1139. * set selection range with a backwards direction: anchor at the
  1140. * back, focus at the front. This means that items that are too
  1141. * long to display will display from the start and not the end
  1142. * even on Firefox.
  1143. *
  1144. * We need the JSNI function to set selection range so that we
  1145. * can use the optional direction attribute to set the anchor to
  1146. * the end and the focus to the start. This makes Firefox work
  1147. * the same way as other browsers (#13477)
  1148. */
  1149. WidgetUtil.setSelectionRange(getElement(), pos, length,
  1150. "backward");
  1151. } else {
  1152. /*
  1153. * Setting the selectionrange for an uneditable textbox leads to
  1154. * unwanted behaviour when the width of the textbox is narrower
  1155. * than the width of the entry: the end of the entry is shown
  1156. * instead of the beginning. (see #13477)
  1157. *
  1158. * To avoid this, we set the caret to the beginning of the line.
  1159. */
  1160. super.setSelectionRange(0, 0);
  1161. }
  1162. }
  1163. }
  1164. /**
  1165. * Handler receiving notifications from the connector and updating the
  1166. * widget state accordingly.
  1167. *
  1168. * This class is still subject to change and should not be considered as
  1169. * public stable API.
  1170. *
  1171. * @since 8.0
  1172. */
  1173. public class DataReceivedHandler {
  1174. private Runnable navigationCallback = null;
  1175. /**
  1176. * Set true when popupopened has been clicked. Cleared on each
  1177. * UIDL-update. This handles the special case where are not filtering
  1178. * yet and the selected value has changed on the server-side. See #2119
  1179. * <p>
  1180. * For internal use only. May be removed or replaced in the future.
  1181. */
  1182. private boolean popupOpenerClicked = false;
  1183. /** For internal use only. May be removed or replaced in the future. */
  1184. private boolean waitingForFilteringResponse = false;
  1185. private boolean initialData = true;
  1186. private String pendingUserInput = null;
  1187. private boolean showPopup = false;
  1188. /**
  1189. * Called by the connector when new data for the last requested filter
  1190. * is received from the server.
  1191. */
  1192. public void dataReceived() {
  1193. if (initialData) {
  1194. suggestionPopup.menu.setSuggestions(currentSuggestions);
  1195. performSelection(serverSelectedKey, true, true);
  1196. updateSuggestionPopupMinWidth();
  1197. updateRootWidth();
  1198. initialData = false;
  1199. return;
  1200. }
  1201. suggestionPopup.menu.setSuggestions(currentSuggestions);
  1202. if (!waitingForFilteringResponse && suggestionPopup.isAttached()) {
  1203. showPopup = true;
  1204. }
  1205. if (showPopup) {
  1206. suggestionPopup.showSuggestions(currentPage, totalMatches);
  1207. }
  1208. waitingForFilteringResponse = false;
  1209. if (pendingUserInput != null) {
  1210. suggestionPopup.menu
  1211. .actOnEnteredValueAfterFiltering(pendingUserInput);
  1212. pendingUserInput = null;
  1213. } else if (popupOpenerClicked) {
  1214. // make sure the current item is selected in the popup
  1215. suggestionPopup.menu.highlightSelectedItem();
  1216. } else {
  1217. navigateItemAfterPageChange();
  1218. }
  1219. if (!showPopup) {
  1220. suggestionPopup.hide();
  1221. }
  1222. popupOpenerClicked = false;
  1223. showPopup = false;
  1224. }
  1225. /**
  1226. * Perform filtering with the user entered string and when the results
  1227. * are received, perform any action appropriate for the user input
  1228. * (select an item or create a new one).
  1229. *
  1230. * @param value
  1231. * user input
  1232. */
  1233. public void reactOnInputWhenReady(String value) {
  1234. pendingUserInput = value;
  1235. showPopup = false;
  1236. filterOptions(0, value);
  1237. }
  1238. /*
  1239. * This method navigates to the proper item in the combobox page. This
  1240. * should be executed after setSuggestions() method which is called from
  1241. * VComboBox.showSuggestions(). ShowSuggestions() method builds the page
  1242. * content. As far as setSuggestions() method is called as deferred,
  1243. * navigateItemAfterPageChange method should be also be called as
  1244. * deferred. #11333
  1245. */
  1246. private void navigateItemAfterPageChange() {
  1247. if (navigationCallback != null) {
  1248. // navigationCallback is not reset here but after any server
  1249. // request in case you are in between two requests both changing
  1250. // the page back and forth
  1251. // we're paging w/ arrows
  1252. navigationCallback.run();
  1253. navigationCallback = null;
  1254. }
  1255. }
  1256. /**
  1257. * Called by the connector any pending navigation operations should be
  1258. * cleared.
  1259. */
  1260. public void clearPendingNavigation() {
  1261. navigationCallback = null;
  1262. }
  1263. /**
  1264. * Set a callback that is invoked when a page change occurs if there
  1265. * have not been intervening requests to the server. The callback is
  1266. * reset when any additional request is made to the server.
  1267. *
  1268. * @param callback
  1269. * method to call after filtering has completed
  1270. */
  1271. public void setNavigationCallback(Runnable callback) {
  1272. showPopup = true;
  1273. navigationCallback = callback;
  1274. }
  1275. /**
  1276. * Record that the popup opener has been clicked and the popup should be
  1277. * opened on the next request.
  1278. *
  1279. * This handles the special case where are not filtering yet and the
  1280. * selected value has changed on the server-side. See #2119. The flag is
  1281. * cleared on each server reply.
  1282. */
  1283. public void popupOpenerClicked() {
  1284. popupOpenerClicked = true;
  1285. showPopup = true;
  1286. }
  1287. /**
  1288. * Cancel a pending request to perform post-filtering actions.
  1289. */
  1290. private void cancelPendingPostFiltering() {
  1291. pendingUserInput = null;
  1292. }
  1293. /**
  1294. * Called by the connector when it has finished handling any reply from
  1295. * the server, regardless of what was updated.
  1296. */
  1297. public void serverReplyHandled() {
  1298. popupOpenerClicked = false;
  1299. lastNewItemString = null;
  1300. // if (!initDone) {
  1301. // debug("VComboBox: init done, updating widths");
  1302. // // Calculate minimum textarea width
  1303. // updateSuggestionPopupMinWidth();
  1304. // updateRootWidth();
  1305. // initDone = true;
  1306. // }
  1307. }
  1308. /**
  1309. * For internal use only - this method will be removed in the future.
  1310. *
  1311. * @return true if the combo box is waiting for a reply from the server
  1312. * with a new page of data, false otherwise
  1313. */
  1314. public boolean isWaitingForFilteringResponse() {
  1315. return waitingForFilteringResponse;
  1316. }
  1317. /**
  1318. * For internal use only - this method will be removed in the future.
  1319. *
  1320. * @return true if the combo box is waiting for initial data from the
  1321. * server, false otherwise
  1322. */
  1323. public boolean isWaitingForInitialData() {
  1324. return initialData;
  1325. }
  1326. /**
  1327. * Set a flag that filtering of options is pending a response from the
  1328. * server.
  1329. */
  1330. private void startWaitingForFilteringResponse() {
  1331. waitingForFilteringResponse = true;
  1332. }
  1333. /**
  1334. * Perform selection (if appropriate) based on a reply from the server.
  1335. * When this method is called, the suggestions have been reset if new
  1336. * ones (different from the previous list) were received from the
  1337. * server.
  1338. *
  1339. * @param selectedKey
  1340. * new selected key or null if none given by the server
  1341. * @param selectedCaption
  1342. * new selected item caption if sent by the server or null -
  1343. * this is used when the selected item is not on the current
  1344. * page
  1345. */
  1346. public void updateSelectionFromServer(String selectedKey,
  1347. String selectedCaption) {
  1348. boolean oldSuggestionTextMatchTheOldSelection = currentSuggestion != null
  1349. && currentSuggestion.getReplacementString()
  1350. .equals(tb.getText());
  1351. serverSelectedKey = selectedKey;
  1352. performSelection(selectedKey, oldSuggestionTextMatchTheOldSelection,
  1353. !isWaitingForFilteringResponse() || popupOpenerClicked);
  1354. cancelPendingPostFiltering();
  1355. setSelectedCaption(selectedCaption);
  1356. if (currentSuggestion != null && serverSelectedKey
  1357. .equals(currentSuggestion.getOptionKey())) {
  1358. setSelectedItemIcon(currentSuggestion.getIconUri());
  1359. }
  1360. }
  1361. }
  1362. // TODO decide whether this should change - affects themes and v7
  1363. public static final String CLASSNAME = "v-filterselect";
  1364. private static final String STYLE_NO_INPUT = "no-input";
  1365. /** For internal use only. May be removed or replaced in the future. */
  1366. public int pageLength = 10;
  1367. private boolean enableDebug = false;
  1368. private final FlowPanel panel = new FlowPanel();
  1369. /**
  1370. * The text box where the filter is written
  1371. * <p>
  1372. * For internal use only. May be removed or replaced in the future.
  1373. */
  1374. public final TextBox tb;
  1375. /** For internal use only. May be removed or replaced in the future. */
  1376. public final SuggestionPopup suggestionPopup;
  1377. /**
  1378. * Used when measuring the width of the popup
  1379. */
  1380. private final HTML popupOpener = new HTML("");
  1381. private class IconWidget extends Widget {
  1382. IconWidget(Icon icon) {
  1383. setElement(icon.getElement());
  1384. }
  1385. }
  1386. private IconWidget selectedItemIcon;
  1387. /** For internal use only. May be removed or replaced in the future. */
  1388. public ComboBoxConnector connector;
  1389. /** For internal use only. May be removed or replaced in the future. */
  1390. public int currentPage;
  1391. /**
  1392. * A collection of available suggestions (options) as received from the
  1393. * server.
  1394. * <p>
  1395. * For internal use only. May be removed or replaced in the future.
  1396. */
  1397. public final List<ComboBoxSuggestion> currentSuggestions = new ArrayList<>();
  1398. /** For internal use only. May be removed or replaced in the future. */
  1399. public String serverSelectedKey;
  1400. /** For internal use only. May be removed or replaced in the future. */
  1401. public String selectedOptionKey;
  1402. /** For internal use only. May be removed or replaced in the future. */
  1403. public boolean initDone = false;
  1404. /** For internal use only. May be removed or replaced in the future. */
  1405. public String lastFilter = "";
  1406. /**
  1407. * The current suggestion selected from the dropdown. This is one of the
  1408. * values in currentSuggestions except when filtering, in this case
  1409. * currentSuggestion might not be in currentSuggestions.
  1410. * <p>
  1411. * For internal use only. May be removed or replaced in the future.
  1412. */
  1413. public ComboBoxSuggestion currentSuggestion;
  1414. /** For internal use only. May be removed or replaced in the future. */
  1415. public boolean allowNewItems;
  1416. /** For internal use only. May be removed or replaced in the future. */
  1417. public int totalMatches;
  1418. /** For internal use only. May be removed or replaced in the future. */
  1419. public boolean nullSelectionAllowed;
  1420. /** For internal use only. May be removed or replaced in the future. */
  1421. public boolean nullSelectItem;
  1422. /** For internal use only. May be removed or replaced in the future. */
  1423. public boolean enabled;
  1424. /** For internal use only. May be removed or replaced in the future. */
  1425. public boolean readonly;
  1426. /** For internal use only. May be removed or replaced in the future. */
  1427. public String inputPrompt = "";
  1428. /** For internal use only. May be removed or replaced in the future. */
  1429. public int suggestionPopupMinWidth = 0;
  1430. public String suggestionPopupWidth = null;
  1431. private int popupWidth = -1;
  1432. /**
  1433. * Stores the last new item string to avoid double submissions. Cleared on
  1434. * uidl updates.
  1435. * <p>
  1436. * For internal use only. May be removed or replaced in the future.
  1437. */
  1438. public String lastNewItemString;
  1439. /** For internal use only. May be removed or replaced in the future. */
  1440. public boolean focused = false;
  1441. /**
  1442. * If set to false, the component should not allow entering text to the
  1443. * field even for filtering.
  1444. */
  1445. private boolean textInputEnabled = true;
  1446. private final DataReceivedHandler dataReceivedHandler = new DataReceivedHandler();
  1447. /**
  1448. * Default constructor.
  1449. */
  1450. public VComboBox() {
  1451. tb = createTextBox();
  1452. suggestionPopup = createSuggestionPopup();
  1453. popupOpener.addMouseDownHandler(VComboBox.this);
  1454. Roles.getButtonRole().setAriaHiddenState(popupOpener.getElement(),
  1455. true);
  1456. Roles.getButtonRole().set(popupOpener.getElement());
  1457. panel.add(tb);
  1458. panel.add(popupOpener);
  1459. initWidget(panel);
  1460. Roles.getComboboxRole().set(panel.getElement());
  1461. tb.addKeyDownHandler(this);
  1462. tb.addKeyUpHandler(this);
  1463. tb.addFocusHandler(this);
  1464. tb.addBlurHandler(this);
  1465. panel.addDomHandler(this, ClickEvent.getType());
  1466. setStyleName(CLASSNAME);
  1467. sinkEvents(Event.ONPASTE);
  1468. }
  1469. private static double getMarginBorderPaddingWidth(Element element) {
  1470. final ComputedStyle s = new ComputedStyle(element);
  1471. return s.getMarginWidth() + s.getBorderWidth() + s.getPaddingWidth();
  1472. }
  1473. /*
  1474. * (non-Javadoc)
  1475. *
  1476. * @see
  1477. * com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt
  1478. * .user.client.Event)
  1479. */
  1480. @Override
  1481. public void onBrowserEvent(Event event) {
  1482. super.onBrowserEvent(event);
  1483. if (event.getTypeInt() == Event.ONPASTE) {
  1484. if (textInputEnabled) {
  1485. filterOptions(currentPage);
  1486. }
  1487. }
  1488. }
  1489. /**
  1490. * This method will create the TextBox used by the VComboBox instance. It is
  1491. * invoked during the Constructor and should only be overridden if a custom
  1492. * TextBox shall be used. The overriding method cannot use any instance
  1493. * variables.
  1494. *
  1495. * @since 7.1.5
  1496. * @return TextBox instance used by this VComboBox
  1497. */
  1498. protected TextBox createTextBox() {
  1499. return new FilterSelectTextBox();
  1500. }
  1501. /**
  1502. * This method will create the SuggestionPopup used by the VComboBox
  1503. * instance. It is invoked during the Constructor and should only be
  1504. * overridden if a custom SuggestionPopup shall be used. The overriding
  1505. * method cannot use any instance variables.
  1506. *
  1507. * @since 7.1.5
  1508. * @return SuggestionPopup instance used by this VComboBox
  1509. */
  1510. protected SuggestionPopup createSuggestionPopup() {
  1511. return new SuggestionPopup();
  1512. }
  1513. @Override
  1514. public void setStyleName(String style) {
  1515. super.setStyleName(style);
  1516. updateStyleNames();
  1517. }
  1518. @Override
  1519. public void setStylePrimaryName(String style) {
  1520. super.setStylePrimaryName(style);
  1521. updateStyleNames();
  1522. }
  1523. protected void updateStyleNames() {
  1524. tb.setStyleName(getStylePrimaryName() + "-input");
  1525. popupOpener.setStyleName(getStylePrimaryName() + "-button");
  1526. suggestionPopup.setStyleName(getStylePrimaryName() + "-suggestpopup");
  1527. }
  1528. /**
  1529. * Does the Select have more pages?
  1530. *
  1531. * @return true if a next page exists, else false if the current page is the
  1532. * last page
  1533. */
  1534. public boolean hasNextPage() {
  1535. return (pageLength > 0
  1536. && totalMatches > (currentPage + 1) * pageLength);
  1537. }
  1538. /**
  1539. * Filters the options at a certain page. Uses the text box input as a
  1540. * filter and ensures the popup is opened when filtering results are
  1541. * available.
  1542. *
  1543. * @param page
  1544. * The page which items are to be filtered
  1545. */
  1546. public void filterOptions(int page) {
  1547. dataReceivedHandler.popupOpenerClicked();
  1548. filterOptions(page, tb.getText());
  1549. }
  1550. /**
  1551. * Filters the options at certain page using the given filter.
  1552. *
  1553. * @param page
  1554. * The page to filter
  1555. * @param filter
  1556. * The filter to apply to the components
  1557. */
  1558. public void filterOptions(int page, String filter) {
  1559. debug("VComboBox: filterOptions(" + page + ", " + filter + ")");
  1560. if (filter.equals(lastFilter) && currentPage == page) {
  1561. if (!suggestionPopup.isAttached()) {
  1562. dataReceivedHandler.startWaitingForFilteringResponse();
  1563. connector.requestPage(currentPage);
  1564. } else {
  1565. // already have the page
  1566. dataReceivedHandler.dataReceived();
  1567. }
  1568. return;
  1569. }
  1570. if (!filter.equals(lastFilter)) {
  1571. // when filtering, let the server decide the page unless we've
  1572. // set the filter to empty and explicitly said that we want to see
  1573. // the results starting from page 0.
  1574. if ("".equals(filter) && page != 0) {
  1575. // let server decide
  1576. page = -1;
  1577. } else {
  1578. page = 0;
  1579. }
  1580. }
  1581. dataReceivedHandler.startWaitingForFilteringResponse();
  1582. connector.setFilter(filter);
  1583. connector.requestPage(currentPage);
  1584. lastFilter = filter;
  1585. currentPage = page;
  1586. }
  1587. /** For internal use only. May be removed or replaced in the future. */
  1588. public void updateReadOnly() {
  1589. debug("VComboBox: updateReadOnly()");
  1590. tb.setReadOnly(readonly || !textInputEnabled);
  1591. }
  1592. public void setTextInputAllowed(boolean textInputAllowed) {
  1593. debug("VComboBox: setTextInputAllowed()");
  1594. // Always update styles as they might have been overwritten
  1595. if (textInputAllowed) {
  1596. removeStyleDependentName(STYLE_NO_INPUT);
  1597. Roles.getTextboxRole().removeAriaReadonlyProperty(tb.getElement());
  1598. } else {
  1599. addStyleDependentName(STYLE_NO_INPUT);
  1600. Roles.getTextboxRole().setAriaReadonlyProperty(tb.getElement(),
  1601. true);
  1602. }
  1603. if (textInputEnabled == textInputAllowed) {
  1604. return;
  1605. }
  1606. textInputEnabled = textInputAllowed;
  1607. updateReadOnly();
  1608. }
  1609. /**
  1610. * Sets the text in the text box.
  1611. *
  1612. * @param text
  1613. * the text to set in the text box
  1614. */
  1615. public void setText(final String text) {
  1616. /**
  1617. * To leave caret in the beginning of the line. SetSelectionRange
  1618. * wouldn't work on IE (see #13477)
  1619. */
  1620. Direction previousDirection = tb.getDirection();
  1621. tb.setDirection(Direction.RTL);
  1622. tb.setText(text);
  1623. tb.setDirection(previousDirection);
  1624. }
  1625. /**
  1626. * Set or reset the placeholder attribute for the text field.
  1627. *
  1628. * @param placeholder
  1629. * new placeholder string or null for none
  1630. */
  1631. public void setPlaceholder(String placeholder) {
  1632. inputPrompt = placeholder;
  1633. updatePlaceholder();
  1634. }
  1635. /**
  1636. * Update placeholder visibility (hidden when read-only or disabled).
  1637. */
  1638. public void updatePlaceholder() {
  1639. if (inputPrompt != null && enabled && !readonly) {
  1640. tb.getElement().setAttribute("placeholder", inputPrompt);
  1641. } else {
  1642. tb.getElement().removeAttribute("placeholder");
  1643. }
  1644. }
  1645. /**
  1646. * Triggered when a suggestion is selected.
  1647. *
  1648. * @param suggestion
  1649. * The suggestion that just got selected.
  1650. */
  1651. public void onSuggestionSelected(ComboBoxSuggestion suggestion) {
  1652. if (enableDebug) {
  1653. debug("VComboBox: onSuggestionSelected(" + suggestion.caption + ": "
  1654. + suggestion.key + ")");
  1655. }
  1656. // special handling of null selection
  1657. if (suggestion.key.equals("")) {
  1658. onNullSelected();
  1659. return;
  1660. }
  1661. dataReceivedHandler.cancelPendingPostFiltering();
  1662. currentSuggestion = suggestion;
  1663. String newKey = suggestion.getOptionKey();
  1664. String text = suggestion.getReplacementString();
  1665. setText(text);
  1666. setSelectedItemIcon(suggestion.getIconUri());
  1667. if (!(newKey.equals(selectedOptionKey))) {
  1668. selectedOptionKey = newKey;
  1669. connector.sendSelection(selectedOptionKey);
  1670. setSelectedCaption(text);
  1671. // currentPage = -1; // forget the page
  1672. }
  1673. suggestionPopup.hide();
  1674. }
  1675. /**
  1676. * Triggered when an empty value is selected and null selection is allowed.
  1677. */
  1678. public void onNullSelected() {
  1679. if (enableDebug) {
  1680. debug("VComboBox: onNullSelected()");
  1681. }
  1682. // TODO do we need this feature?
  1683. if (nullSelectItem) {
  1684. reset();
  1685. return;
  1686. }
  1687. dataReceivedHandler.cancelPendingPostFiltering();
  1688. currentSuggestion = null;
  1689. setText("");
  1690. setSelectedItemIcon(null);
  1691. if (!"".equals(selectedOptionKey) || (selectedOptionKey != null)) {
  1692. selectedOptionKey = "";
  1693. setSelectedCaption("");
  1694. connector.sendSelection(null);
  1695. // currentPage = 0;
  1696. }
  1697. suggestionPopup.hide();
  1698. }
  1699. /**
  1700. * Sets the icon URI of the selected item. The icon is shown on the left
  1701. * side of the item caption text. Set the URI to null to remove the icon.
  1702. *
  1703. * @param iconUri
  1704. * The URI of the icon
  1705. */
  1706. public void setSelectedItemIcon(String iconUri) {
  1707. if (selectedItemIcon != null) {
  1708. panel.remove(selectedItemIcon);
  1709. }
  1710. if (iconUri == null || iconUri.length() == 0) {
  1711. if (selectedItemIcon != null) {
  1712. selectedItemIcon = null;
  1713. afterSelectedItemIconChange();
  1714. }
  1715. } else {
  1716. selectedItemIcon = new IconWidget(
  1717. connector.getConnection().getIcon(iconUri));
  1718. selectedItemIcon.addDomHandler(VComboBox.this,
  1719. ClickEvent.getType());
  1720. selectedItemIcon.addDomHandler(VComboBox.this,
  1721. MouseDownEvent.getType());
  1722. iconUpdating = true;
  1723. selectedItemIcon.addDomHandler(new LoadHandler() {
  1724. @Override
  1725. public void onLoad(LoadEvent event) {
  1726. afterSelectedItemIconChange();
  1727. iconUpdating = false;
  1728. }
  1729. }, LoadEvent.getType());
  1730. panel.insert(selectedItemIcon, 0);
  1731. afterSelectedItemIconChange();
  1732. }
  1733. }
  1734. private void afterSelectedItemIconChange() {
  1735. if (BrowserInfo.get().isWebkit()) {
  1736. // Some browsers need a nudge to reposition the text field
  1737. forceReflow();
  1738. }
  1739. updateRootWidth();
  1740. if (selectedItemIcon != null) {
  1741. updateSelectedIconPosition();
  1742. }
  1743. }
  1744. /**
  1745. * Perform selection based on a message from the server.
  1746. *
  1747. * The special case where the selected item is not on the current page is
  1748. * handled separately by the caller.
  1749. *
  1750. * @param selectedKey
  1751. * non-empty selected item key
  1752. * @param forceUpdateText
  1753. * true to force the text box value to match the suggestion text
  1754. * @param updatePromptAndSelectionIfMatchFound
  1755. */
  1756. private void performSelection(String selectedKey, boolean forceUpdateText,
  1757. boolean updatePromptAndSelectionIfMatchFound) {
  1758. if (selectedKey == null || "".equals(selectedKey)) {
  1759. currentSuggestion = null; // #13217
  1760. setSelectedItemIcon(null);
  1761. selectedOptionKey = null;
  1762. setText("");
  1763. }
  1764. // some item selected
  1765. for (ComboBoxSuggestion suggestion : currentSuggestions) {
  1766. String suggestionKey = suggestion.getOptionKey();
  1767. if (!suggestionKey.equals(selectedKey)) {
  1768. continue;
  1769. }
  1770. // at this point, suggestion key matches the new selection key
  1771. if (updatePromptAndSelectionIfMatchFound) {
  1772. if (!suggestionKey.equals(selectedOptionKey) || suggestion
  1773. .getReplacementString().equals(tb.getText())
  1774. || forceUpdateText) {
  1775. // Update text field if we've got a new
  1776. // selection
  1777. // Also update if we've got the same text to
  1778. // retain old text selection behavior
  1779. // OR if selected item caption is changed.
  1780. setText(suggestion.getReplacementString());
  1781. selectedOptionKey = suggestionKey;
  1782. }
  1783. }
  1784. currentSuggestion = suggestion;
  1785. setSelectedItemIcon(suggestion.getIconUri());
  1786. // only a single item can be selected
  1787. break;
  1788. }
  1789. }
  1790. private void forceReflow() {
  1791. WidgetUtil.setStyleTemporarily(tb.getElement(), "zoom", "1");
  1792. }
  1793. /**
  1794. * Positions the icon vertically in the middle. Should be called after the
  1795. * icon has loaded
  1796. */
  1797. private void updateSelectedIconPosition() {
  1798. // Position icon vertically to middle
  1799. int availableHeight = 0;
  1800. availableHeight = getOffsetHeight();
  1801. int iconHeight = WidgetUtil.getRequiredHeight(selectedItemIcon);
  1802. int marginTop = (availableHeight - iconHeight) / 2;
  1803. selectedItemIcon.getElement().getStyle().setMarginTop(marginTop,
  1804. Unit.PX);
  1805. }
  1806. private static Set<Integer> navigationKeyCodes = new HashSet<>();
  1807. static {
  1808. navigationKeyCodes.add(KeyCodes.KEY_DOWN);
  1809. navigationKeyCodes.add(KeyCodes.KEY_UP);
  1810. navigationKeyCodes.add(KeyCodes.KEY_PAGEDOWN);
  1811. navigationKeyCodes.add(KeyCodes.KEY_PAGEUP);
  1812. navigationKeyCodes.add(KeyCodes.KEY_ENTER);
  1813. }
  1814. /*
  1815. * (non-Javadoc)
  1816. *
  1817. * @see
  1818. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1819. * .event.dom.client.KeyDownEvent)
  1820. */
  1821. @Override
  1822. public void onKeyDown(KeyDownEvent event) {
  1823. if (enabled && !readonly) {
  1824. int keyCode = event.getNativeKeyCode();
  1825. if (enableDebug) {
  1826. debug("VComboBox: key down: " + keyCode);
  1827. }
  1828. if (dataReceivedHandler.isWaitingForFilteringResponse()
  1829. && navigationKeyCodes.contains(keyCode)
  1830. && (!allowNewItems || keyCode != KeyCodes.KEY_ENTER)) {
  1831. /*
  1832. * Keyboard navigation events should not be handled while we are
  1833. * waiting for a response. This avoids flickering, disappearing
  1834. * items, wrongly interpreted responses and more.
  1835. */
  1836. if (enableDebug) {
  1837. debug("Ignoring " + keyCode
  1838. + " because we are waiting for a filtering response");
  1839. }
  1840. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1841. event.stopPropagation();
  1842. return;
  1843. }
  1844. if (suggestionPopup.isAttached()) {
  1845. if (enableDebug) {
  1846. debug("Keycode " + keyCode + " target is popup");
  1847. }
  1848. popupKeyDown(event);
  1849. } else {
  1850. if (enableDebug) {
  1851. debug("Keycode " + keyCode + " target is text field");
  1852. }
  1853. inputFieldKeyDown(event);
  1854. }
  1855. }
  1856. }
  1857. private void debug(String string) {
  1858. if (enableDebug) {
  1859. VConsole.error(string);
  1860. }
  1861. }
  1862. /**
  1863. * Triggered when a key is pressed in the text box
  1864. *
  1865. * @param event
  1866. * The KeyDownEvent
  1867. */
  1868. private void inputFieldKeyDown(KeyDownEvent event) {
  1869. if (enableDebug) {
  1870. debug("VComboBox: inputFieldKeyDown(" + event.getNativeKeyCode()
  1871. + ")");
  1872. }
  1873. switch (event.getNativeKeyCode()) {
  1874. case KeyCodes.KEY_DOWN:
  1875. case KeyCodes.KEY_UP:
  1876. case KeyCodes.KEY_PAGEDOWN:
  1877. case KeyCodes.KEY_PAGEUP:
  1878. // open popup as from gadget
  1879. filterOptions(-1, "");
  1880. tb.selectAll();
  1881. dataReceivedHandler.popupOpenerClicked();
  1882. break;
  1883. case KeyCodes.KEY_ENTER:
  1884. /*
  1885. * This only handles the case when new items is allowed, a text is
  1886. * entered, the popup opener button is clicked to close the popup
  1887. * and enter is then pressed (see #7560).
  1888. */
  1889. if (!allowNewItems) {
  1890. return;
  1891. }
  1892. if (currentSuggestion != null && tb.getText()
  1893. .equals(currentSuggestion.getReplacementString())) {
  1894. // Retain behavior from #6686 by returning without stopping
  1895. // propagation if there's nothing to do
  1896. return;
  1897. }
  1898. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  1899. suggestionPopup.hide();
  1900. event.stopPropagation();
  1901. break;
  1902. }
  1903. }
  1904. /**
  1905. * Triggered when a key was pressed in the suggestion popup.
  1906. *
  1907. * @param event
  1908. * The KeyDownEvent of the key
  1909. */
  1910. private void popupKeyDown(KeyDownEvent event) {
  1911. if (enableDebug) {
  1912. debug("VComboBox: popupKeyDown(" + event.getNativeKeyCode() + ")");
  1913. }
  1914. // Propagation of handled events is stopped so other handlers such as
  1915. // shortcut key handlers do not also handle the same events.
  1916. switch (event.getNativeKeyCode()) {
  1917. case KeyCodes.KEY_DOWN:
  1918. suggestionPopup.selectNextItem();
  1919. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1920. event.stopPropagation();
  1921. break;
  1922. case KeyCodes.KEY_UP:
  1923. suggestionPopup.selectPrevItem();
  1924. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1925. event.stopPropagation();
  1926. break;
  1927. case KeyCodes.KEY_PAGEDOWN:
  1928. selectNextPage();
  1929. event.stopPropagation();
  1930. break;
  1931. case KeyCodes.KEY_PAGEUP:
  1932. selectPrevPage();
  1933. event.stopPropagation();
  1934. break;
  1935. case KeyCodes.KEY_ESCAPE:
  1936. reset();
  1937. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1938. event.stopPropagation();
  1939. break;
  1940. case KeyCodes.KEY_TAB:
  1941. case KeyCodes.KEY_ENTER:
  1942. // queue this, may be cancelled by selection
  1943. int selectedIndex = suggestionPopup.menu.getSelectedIndex();
  1944. if (!allowNewItems && selectedIndex != -1) {
  1945. onSuggestionSelected(currentSuggestions.get(selectedIndex));
  1946. } else {
  1947. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  1948. }
  1949. suggestionPopup.hide();
  1950. event.stopPropagation();
  1951. break;
  1952. }
  1953. }
  1954. /*
  1955. * Show the prev page.
  1956. */
  1957. private void selectPrevPage() {
  1958. if (currentPage > 0) {
  1959. dataReceivedHandler.setNavigationCallback(
  1960. () -> suggestionPopup.selectLastItem());
  1961. filterOptions(currentPage - 1, lastFilter);
  1962. }
  1963. }
  1964. /*
  1965. * Show the next page.
  1966. */
  1967. private void selectNextPage() {
  1968. if (hasNextPage()) {
  1969. dataReceivedHandler.setNavigationCallback(
  1970. () -> suggestionPopup.selectFirstItem());
  1971. filterOptions(currentPage + 1, lastFilter);
  1972. }
  1973. }
  1974. /**
  1975. * Triggered when a key was depressed.
  1976. *
  1977. * @param event
  1978. * The KeyUpEvent of the key depressed
  1979. */
  1980. @Override
  1981. public void onKeyUp(KeyUpEvent event) {
  1982. if (enableDebug) {
  1983. debug("VComboBox: onKeyUp(" + event.getNativeKeyCode() + ")");
  1984. }
  1985. if (enabled && !readonly) {
  1986. switch (event.getNativeKeyCode()) {
  1987. case KeyCodes.KEY_ENTER:
  1988. case KeyCodes.KEY_TAB:
  1989. case KeyCodes.KEY_SHIFT:
  1990. case KeyCodes.KEY_CTRL:
  1991. case KeyCodes.KEY_ALT:
  1992. case KeyCodes.KEY_DOWN:
  1993. case KeyCodes.KEY_UP:
  1994. case KeyCodes.KEY_PAGEDOWN:
  1995. case KeyCodes.KEY_PAGEUP:
  1996. case KeyCodes.KEY_ESCAPE:
  1997. // NOP
  1998. break;
  1999. default:
  2000. if (textInputEnabled) {
  2001. // when filtering, we always want to see the results on the
  2002. // first page first.
  2003. filterOptions(0);
  2004. }
  2005. break;
  2006. }
  2007. }
  2008. }
  2009. /**
  2010. * Resets the ComboBox to its initial state.
  2011. */
  2012. private void reset() {
  2013. debug("VComboBox: reset()");
  2014. if (currentSuggestion != null) {
  2015. String text = currentSuggestion.getReplacementString();
  2016. setText(text);
  2017. setSelectedItemIcon(currentSuggestion.getIconUri());
  2018. selectedOptionKey = currentSuggestion.key;
  2019. } else {
  2020. setText("");
  2021. setSelectedItemIcon(null);
  2022. updatePlaceholder();
  2023. selectedOptionKey = null;
  2024. }
  2025. lastFilter = "";
  2026. suggestionPopup.hide();
  2027. }
  2028. /**
  2029. * Listener for popupopener.
  2030. */
  2031. @Override
  2032. public void onClick(ClickEvent event) {
  2033. debug("VComboBox: onClick()");
  2034. if (textInputEnabled && event.getNativeEvent().getEventTarget()
  2035. .cast() == tb.getElement()) {
  2036. // Don't process clicks on the text field if text input is enabled
  2037. return;
  2038. }
  2039. if (enabled && !readonly) {
  2040. // ask suggestionPopup if it was just closed, we are using GWT
  2041. // Popup's auto close feature
  2042. if (!suggestionPopup.isJustClosed()) {
  2043. filterOptions(-1, "");
  2044. dataReceivedHandler.popupOpenerClicked();
  2045. }
  2046. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2047. focus();
  2048. tb.selectAll();
  2049. }
  2050. }
  2051. /**
  2052. * Update minimum width for combo box textarea based on input prompt and
  2053. * suggestions.
  2054. * <p>
  2055. * For internal use only. May be removed or replaced in the future.
  2056. */
  2057. public void updateSuggestionPopupMinWidth() {
  2058. debug("VComboBox: updateSuggestionPopupMinWidth()");
  2059. // used only to calculate minimum width
  2060. String captions = WidgetUtil.escapeHTML(inputPrompt);
  2061. for (ComboBoxSuggestion suggestion : currentSuggestions) {
  2062. // Collect captions so we can calculate minimum width for
  2063. // textarea
  2064. if (captions.length() > 0) {
  2065. captions += "|";
  2066. }
  2067. captions += WidgetUtil
  2068. .escapeHTML(suggestion.getReplacementString());
  2069. }
  2070. // Calculate minimum textarea width
  2071. suggestionPopupMinWidth = minWidth(captions);
  2072. }
  2073. /**
  2074. * Calculate minimum width for FilterSelect textarea.
  2075. * <p>
  2076. * For internal use only. May be removed or replaced in the future.
  2077. *
  2078. * @param captions
  2079. * pipe separated string listing all the captions to measure
  2080. * @return minimum width in pixels
  2081. */
  2082. public native int minWidth(String captions)
  2083. /*-{
  2084. if(!captions || captions.length <= 0)
  2085. return 0;
  2086. captions = captions.split("|");
  2087. var d = $wnd.document.createElement("div");
  2088. var html = "";
  2089. for(var i=0; i < captions.length; i++) {
  2090. html += "<div>" + captions[i] + "</div>";
  2091. // TODO apply same CSS classname as in suggestionmenu
  2092. }
  2093. d.style.position = "absolute";
  2094. d.style.top = "0";
  2095. d.style.left = "0";
  2096. d.style.visibility = "hidden";
  2097. d.innerHTML = html;
  2098. $wnd.document.body.appendChild(d);
  2099. var w = d.offsetWidth;
  2100. $wnd.document.body.removeChild(d);
  2101. return w;
  2102. }-*/;
  2103. /**
  2104. * A flag which prevents a focus event from taking place.
  2105. */
  2106. boolean iePreventNextFocus = false;
  2107. /*
  2108. * (non-Javadoc)
  2109. *
  2110. * @see
  2111. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  2112. * .dom.client.FocusEvent)
  2113. */
  2114. @Override
  2115. public void onFocus(FocusEvent event) {
  2116. debug("VComboBox: onFocus()");
  2117. /*
  2118. * When we disable a blur event in ie we need to refocus the textfield.
  2119. * This will cause a focus event we do not want to process, so in that
  2120. * case we just ignore it.
  2121. */
  2122. if (BrowserInfo.get().isIE() && iePreventNextFocus) {
  2123. iePreventNextFocus = false;
  2124. return;
  2125. }
  2126. focused = true;
  2127. updatePlaceholder();
  2128. addStyleDependentName("focus");
  2129. connector.sendFocusEvent();
  2130. connector.getConnection().getVTooltip()
  2131. .showAssistive(connector.getTooltipInfo(getElement()));
  2132. }
  2133. /**
  2134. * A flag which cancels the blur event and sets the focus back to the
  2135. * textfield if the Browser is IE.
  2136. */
  2137. boolean preventNextBlurEventInIE = false;
  2138. private String explicitSelectedCaption;
  2139. private boolean iconUpdating = false;
  2140. /*
  2141. * (non-Javadoc)
  2142. *
  2143. * @see
  2144. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  2145. * .dom.client.BlurEvent)
  2146. */
  2147. @Override
  2148. public void onBlur(BlurEvent event) {
  2149. debug("VComboBox: onBlur()");
  2150. if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) {
  2151. /*
  2152. * Clicking in the suggestion popup or on the popup button in IE
  2153. * causes a blur event to be sent for the field. In other browsers
  2154. * this is prevented by canceling/preventing default behavior for
  2155. * the focus event, in IE we handle it here by refocusing the text
  2156. * field and ignoring the resulting focus event for the textfield
  2157. * (in onFocus).
  2158. */
  2159. preventNextBlurEventInIE = false;
  2160. Element focusedElement = WidgetUtil.getFocusedElement();
  2161. if (getElement().isOrHasChild(focusedElement) || suggestionPopup
  2162. .getElement().isOrHasChild(focusedElement)) {
  2163. // IF the suggestion popup or another part of the VComboBox
  2164. // was focused, move the focus back to the textfield and prevent
  2165. // the triggered focus event (in onFocus).
  2166. iePreventNextFocus = true;
  2167. tb.setFocus(true);
  2168. return;
  2169. }
  2170. }
  2171. focused = false;
  2172. updatePlaceholder();
  2173. if (!readonly) {
  2174. reset();
  2175. suggestionPopup.hide();
  2176. }
  2177. removeStyleDependentName("focus");
  2178. connector.sendBlurEvent();
  2179. }
  2180. /*
  2181. * (non-Javadoc)
  2182. *
  2183. * @see com.vaadin.client.Focusable#focus()
  2184. */
  2185. @Override
  2186. public void focus() {
  2187. debug("VComboBox: focus()");
  2188. focused = true;
  2189. updatePlaceholder();
  2190. tb.setFocus(true);
  2191. }
  2192. /**
  2193. * Calculates the width of the select if the select has undefined width.
  2194. * Should be called when the width changes or when the icon changes.
  2195. * <p>
  2196. * For internal use only. May be removed or replaced in the future.
  2197. */
  2198. public void updateRootWidth() {
  2199. debug("VComboBox: updateRootWidth()");
  2200. if (connector.isUndefinedWidth()) {
  2201. /*
  2202. * When the select has a undefined with we need to check that we are
  2203. * only setting the text box width relative to the first page width
  2204. * of the items. If this is not done the text box width will change
  2205. * when the popup is used to view longer items than the text box is
  2206. * wide.
  2207. */
  2208. int w = WidgetUtil.getRequiredWidth(this);
  2209. if (dataReceivedHandler.isWaitingForInitialData()
  2210. && suggestionPopupMinWidth > w) {
  2211. /*
  2212. * We want to compensate for the paddings just to preserve the
  2213. * exact size as in Vaadin 6.x, but we get here before
  2214. * MeasuredSize has been initialized.
  2215. * Util.measureHorizontalPaddingAndBorder does not work with
  2216. * border-box, so we must do this the hard way.
  2217. */
  2218. Style style = getElement().getStyle();
  2219. String originalPadding = style.getPadding();
  2220. String originalBorder = style.getBorderWidth();
  2221. style.setPaddingLeft(0, Unit.PX);
  2222. style.setBorderWidth(0, Unit.PX);
  2223. style.setProperty("padding", originalPadding);
  2224. style.setProperty("borderWidth", originalBorder);
  2225. // Use util.getRequiredWidth instead of getOffsetWidth here
  2226. int iconWidth = selectedItemIcon == null ? 0
  2227. : WidgetUtil.getRequiredWidth(selectedItemIcon);
  2228. int buttonWidth = popupOpener == null ? 0
  2229. : WidgetUtil.getRequiredWidth(popupOpener);
  2230. /*
  2231. * Instead of setting the width of the wrapper, set the width of
  2232. * the combobox. Subtract the width of the icon and the
  2233. * popupopener
  2234. */
  2235. tb.setWidth((suggestionPopupMinWidth - iconWidth - buttonWidth)
  2236. + "px");
  2237. }
  2238. /*
  2239. * Lock the textbox width to its current value if it's not already
  2240. * locked. This can happen after setWidth("") which resets the
  2241. * textbox width to "100%".
  2242. */
  2243. if (!tb.getElement().getStyle().getWidth().endsWith("px")) {
  2244. int iconWidth = selectedItemIcon == null ? 0
  2245. : selectedItemIcon.getOffsetWidth();
  2246. tb.setWidth((tb.getOffsetWidth() - iconWidth) + "px");
  2247. }
  2248. }
  2249. }
  2250. /**
  2251. * Get the width of the select in pixels where the text area and icon has
  2252. * been included.
  2253. *
  2254. * @return The width in pixels
  2255. */
  2256. private int getMainWidth() {
  2257. return getOffsetWidth();
  2258. }
  2259. @Override
  2260. public void setWidth(String width) {
  2261. super.setWidth(width);
  2262. if (width.length() != 0) {
  2263. tb.setWidth("100%");
  2264. }
  2265. }
  2266. /**
  2267. * Handles special behavior of the mouse down event.
  2268. *
  2269. * @param event
  2270. */
  2271. private void handleMouseDownEvent(Event event) {
  2272. /*
  2273. * Prevent the keyboard focus from leaving the textfield by preventing
  2274. * the default behaviour of the browser. Fixes #4285.
  2275. */
  2276. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  2277. debug("VComboBox: blocking mouseDown event to avoid blur");
  2278. event.preventDefault();
  2279. event.stopPropagation();
  2280. /*
  2281. * In IE the above wont work, the blur event will still trigger. So,
  2282. * we set a flag here to prevent the next blur event from happening.
  2283. * This is not needed if do not already have focus, in that case
  2284. * there will not be any blur event and we should not cancel the
  2285. * next blur.
  2286. */
  2287. if (BrowserInfo.get().isIE() && focused) {
  2288. preventNextBlurEventInIE = true;
  2289. debug("VComboBox: Going to prevent next blur event on IE");
  2290. }
  2291. }
  2292. }
  2293. @Override
  2294. public void onMouseDown(MouseDownEvent event) {
  2295. debug("VComboBox.onMouseDown(): blocking mouseDown event to avoid blur");
  2296. event.preventDefault();
  2297. event.stopPropagation();
  2298. /*
  2299. * In IE the above wont work, the blur event will still trigger. So, we
  2300. * set a flag here to prevent the next blur event from happening. This
  2301. * is not needed if do not already have focus, in that case there will
  2302. * not be any blur event and we should not cancel the next blur.
  2303. */
  2304. if (BrowserInfo.get().isIE() && focused) {
  2305. preventNextBlurEventInIE = true;
  2306. debug("VComboBox: Going to prevent next blur event on IE");
  2307. }
  2308. }
  2309. @Override
  2310. protected void onDetach() {
  2311. super.onDetach();
  2312. suggestionPopup.hide();
  2313. }
  2314. @Override
  2315. public com.google.gwt.user.client.Element getSubPartElement(
  2316. String subPart) {
  2317. String[] parts = subPart.split("/");
  2318. if ("textbox".equals(parts[0])) {
  2319. return tb.getElement();
  2320. } else if ("button".equals(parts[0])) {
  2321. return popupOpener.getElement();
  2322. } else if ("popup".equals(parts[0]) && suggestionPopup.isAttached()) {
  2323. if (parts.length == 2) {
  2324. return suggestionPopup.menu.getSubPartElement(parts[1]);
  2325. }
  2326. return suggestionPopup.getElement();
  2327. }
  2328. return null;
  2329. }
  2330. @Override
  2331. public String getSubPartName(
  2332. com.google.gwt.user.client.Element subElement) {
  2333. if (tb.getElement().isOrHasChild(subElement)) {
  2334. return "textbox";
  2335. } else if (popupOpener.getElement().isOrHasChild(subElement)) {
  2336. return "button";
  2337. } else if (suggestionPopup.getElement().isOrHasChild(subElement)) {
  2338. return "popup";
  2339. }
  2340. return null;
  2341. }
  2342. @Override
  2343. public void setAriaRequired(boolean required) {
  2344. AriaHelper.handleInputRequired(tb, required);
  2345. }
  2346. @Override
  2347. public void setAriaInvalid(boolean invalid) {
  2348. AriaHelper.handleInputInvalid(tb, invalid);
  2349. }
  2350. @Override
  2351. public void bindAriaCaption(
  2352. com.google.gwt.user.client.Element captionElement) {
  2353. AriaHelper.bindCaption(tb, captionElement);
  2354. }
  2355. @Override
  2356. public boolean isWorkPending() {
  2357. return dataReceivedHandler.isWaitingForFilteringResponse()
  2358. || suggestionPopup.lazyPageScroller.isRunning() || iconUpdating;
  2359. }
  2360. /**
  2361. * Sets the caption of selected item, if "scroll to page" is disabled. This
  2362. * method is meant for internal use and may change in future versions.
  2363. *
  2364. * @since 7.7
  2365. * @param selectedCaption
  2366. * the caption of selected item
  2367. */
  2368. public void setSelectedCaption(String selectedCaption) {
  2369. explicitSelectedCaption = selectedCaption;
  2370. if (selectedCaption != null) {
  2371. setText(selectedCaption);
  2372. }
  2373. }
  2374. /**
  2375. * This method is meant for internal use and may change in future versions.
  2376. *
  2377. * @since 7.7
  2378. * @return the caption of selected item, if "scroll to page" is disabled
  2379. */
  2380. public String getSelectedCaption() {
  2381. return explicitSelectedCaption;
  2382. }
  2383. /**
  2384. * Returns a handler receiving notifications from the connector about
  2385. * communications.
  2386. *
  2387. * @return the dataReceivedHandler
  2388. */
  2389. public DataReceivedHandler getDataReceivedHandler() {
  2390. return dataReceivedHandler;
  2391. }
  2392. /**
  2393. * Sets the number of items to show per page, or 0 for showing all items.
  2394. *
  2395. * @param pageLength
  2396. * new page length or 0 for all items
  2397. */
  2398. public void setPageLength(int pageLength) {
  2399. this.pageLength = pageLength;
  2400. }
  2401. /**
  2402. * Sets the suggestion pop-up's width as a CSS string. By using relative
  2403. * units (e.g. "50%") it's possible to set the popup's width relative to the
  2404. * ComboBox itself.
  2405. *
  2406. * @param suggestionPopupWidth
  2407. * new popup width as CSS string, null for old default width
  2408. * calculation based on items
  2409. */
  2410. public void setSuggestionPopupWidth(String suggestionPopupWidth) {
  2411. this.suggestionPopupWidth = suggestionPopupWidth;
  2412. }
  2413. /**
  2414. * Sets whether creation of new items when there is no match is allowed or
  2415. * not.
  2416. *
  2417. * @param allowNewItems
  2418. * true to allow creation of new items, false to only allow
  2419. * selection of existing items
  2420. */
  2421. public void setAllowNewItems(boolean allowNewItems) {
  2422. this.allowNewItems = allowNewItems;
  2423. }
  2424. }