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

VComboBox.java 108KB

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