您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

VComboBox.java 101KB

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