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

VComboBox.java 105KB

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