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 101KB

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