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.

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