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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066
  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 (hasParentWithUnadjustedHorizontalPositioning()) {
  791. // ComboBox itself may be incorrectly positioned, don't try to
  792. // adjust horizontal popup position yet. Earlier width
  793. // calculations must be performed anyway to avoid flickering.
  794. if (top != topPosition) {
  795. // Variable 'left' still contains the original popupLeft,
  796. // 'top' has been updated, thus vertical position needs
  797. // adjusting.
  798. setPopupPosition(left, top);
  799. }
  800. return;
  801. }
  802. if (left > comboBoxLeft
  803. || offsetWidth + menuMarginBorderPaddingWidth
  804. + left < comboBoxLeft + comboBoxWidth) {
  805. // Popup is positioned too far right or doesn't reach all the
  806. // way to the end of the input field, filtering may have changed
  807. // the popup width.
  808. left = comboBoxLeft;
  809. }
  810. if (offsetWidth + menuMarginBorderPaddingWidth + left > Window
  811. .getClientWidth()) {
  812. // Popup doesn't fit the view, needs to be opened to the left
  813. // instead.
  814. left = comboBoxLeft + comboBoxWidth - offsetWidth
  815. - (int) menuMarginBorderPaddingWidth;
  816. }
  817. if (left < 0) {
  818. left = 0;
  819. menu.setWidth(Window.getClientWidth() + "px");
  820. }
  821. // Only update the position if it has changed.
  822. if (top != topPosition || left != getPopupLeft()) {
  823. setPopupPosition(left, top);
  824. }
  825. menu.scrollSelectionIntoView();
  826. }
  827. /**
  828. * Checks whether there are any {@link VHorizontalLayout}s with
  829. * incomplete internal position calculations among this VComboBox's
  830. * parents.
  831. *
  832. * @return {@code true} if unadjusted parents found, {@code false}
  833. * otherwise
  834. */
  835. private boolean hasParentWithUnadjustedHorizontalPositioning() {
  836. /*
  837. * If there are any VHorizontalLayouts among this VComboBox's
  838. * parents, any spacing or expand ratio may cause incorrect
  839. * intermediate positioning. The status of the layout's internal
  840. * positioning can be checked from the first slot's margin-left
  841. * style, which will be set to 0px if no spacing or expand ratio
  842. * adjustments are needed, and to a negative pixel amount if they
  843. * are. If the style hasn't been set at all, calculations are still
  844. * underway. Popup position shouldn't be adjusted before such
  845. * calculations have been finished.
  846. *
  847. * VVerticalLayout has the same logic but it only affects the
  848. * vertical positioning, which is irrelevant for the calculations
  849. * here.
  850. */
  851. Widget toCheck = VComboBox.this;
  852. while (toCheck != null && !(toCheck.getParent() instanceof VUI)) {
  853. toCheck = toCheck.getParent();
  854. if (toCheck instanceof VHorizontalLayout) {
  855. VHorizontalLayout hLayout = (VHorizontalLayout) toCheck;
  856. // because hLayout is a parent it must have at least one
  857. // child widget
  858. Widget slot = hLayout.getWidget(0);
  859. if (slot instanceof Slot && slot.getElement().getStyle()
  860. .getMarginLeft().isEmpty()) {
  861. // margin hasn't been set, layout's internal positioning
  862. // is still being adjusted and ComboBox's position may
  863. // not be final
  864. return true;
  865. }
  866. }
  867. }
  868. return false;
  869. }
  870. /**
  871. * Adds in-line CSS rules to the DOM according to the
  872. * suggestionPopupWidth field
  873. *
  874. * @param desiredWidth
  875. * @param naturalMenuWidth
  876. */
  877. private void updateMenuWidth(final int desiredWidth,
  878. int naturalMenuWidth) {
  879. /**
  880. * Three different width modes for the suggestion pop-up:
  881. *
  882. * 1. Legacy "null"-mode: width is determined by the longest item
  883. * caption for each page while still maintaining minimum width of
  884. * (desiredWidth - popupOuterPadding)
  885. *
  886. * 2. relative to the component itself
  887. *
  888. * 3. fixed width
  889. */
  890. String width = "auto";
  891. if (suggestionPopupWidth == null) {
  892. if (naturalMenuWidth < desiredWidth) {
  893. naturalMenuWidth = desiredWidth - popupOuterPadding;
  894. width = desiredWidth - popupOuterPadding + "px";
  895. }
  896. } else if (isrelativeUnits(suggestionPopupWidth)) {
  897. float mainComponentWidth = desiredWidth - popupOuterPadding;
  898. // convert percentage value to fraction
  899. int widthInPx = Math.round(
  900. mainComponentWidth * asFraction(suggestionPopupWidth));
  901. width = widthInPx + "px";
  902. } else {
  903. // use as fixed width CSS definition
  904. width = WidgetUtil.escapeAttribute(suggestionPopupWidth);
  905. }
  906. menu.setWidth(width);
  907. }
  908. /**
  909. * Returns the percentage value as a fraction, e.g. 42% -> 0.42
  910. *
  911. * @param percentage
  912. */
  913. private float asFraction(String percentage) {
  914. String trimmed = percentage.trim();
  915. String withoutPercentSign = trimmed.substring(0,
  916. trimmed.length() - 1);
  917. float asFraction = Float.parseFloat(withoutPercentSign) / 100;
  918. return asFraction;
  919. }
  920. /**
  921. * @since 7.7
  922. * @param suggestionPopupWidth
  923. * @return
  924. */
  925. private boolean isrelativeUnits(String suggestionPopupWidth) {
  926. return suggestionPopupWidth.trim().endsWith("%");
  927. }
  928. /**
  929. * Was the popup just closed?
  930. *
  931. * @return true if popup was just closed
  932. */
  933. public boolean isJustClosed() {
  934. debug("VComboBox.SP: justClosed()");
  935. final long now = new Date().getTime();
  936. return lastAutoClosed > 0 && now - lastAutoClosed < 200;
  937. }
  938. /*
  939. * (non-Javadoc)
  940. *
  941. * @see
  942. * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google
  943. * .gwt.event.logical.shared.CloseEvent)
  944. */
  945. @Override
  946. public void onClose(CloseEvent<PopupPanel> event) {
  947. if (enableDebug) {
  948. debug("VComboBox.SP: onClose(" + event.isAutoClosed() + ")");
  949. }
  950. if (event.isAutoClosed()) {
  951. lastAutoClosed = new Date().getTime();
  952. }
  953. }
  954. /**
  955. * Updates style names in suggestion popup to help theme building.
  956. *
  957. * @param componentState
  958. * shared state of the combo box
  959. */
  960. public void updateStyleNames(AbstractComponentState componentState) {
  961. debug("VComboBox.SP: updateStyleNames()");
  962. setStyleName(
  963. VComboBox.this.getStylePrimaryName() + "-suggestpopup");
  964. menu.setStyleName(
  965. VComboBox.this.getStylePrimaryName() + "-suggestmenu");
  966. status.setClassName(
  967. VComboBox.this.getStylePrimaryName() + "-status");
  968. if (ComponentStateUtil.hasStyles(componentState)) {
  969. for (String style : componentState.styles) {
  970. if (!"".equals(style)) {
  971. addStyleDependentName(style);
  972. }
  973. }
  974. }
  975. }
  976. }
  977. /**
  978. * The menu where the suggestions are rendered.
  979. */
  980. public class SuggestionMenu extends MenuBar
  981. implements SubPartAware, LoadHandler {
  982. private VLazyExecutor delayedImageLoadExecutioner = new VLazyExecutor(
  983. 100, () -> {
  984. debug("VComboBox.SM: delayedImageLoadExecutioner()");
  985. if (suggestionPopup.isVisible()
  986. && suggestionPopup.isAttached()) {
  987. setWidth("");
  988. getElement().getFirstChildElement().getStyle()
  989. .clearWidth();
  990. suggestionPopup
  991. .setPopupPositionAndShow(suggestionPopup);
  992. }
  993. });
  994. private String handledNewItem = null;
  995. /**
  996. * Default constructor
  997. */
  998. SuggestionMenu() {
  999. super(true);
  1000. debug("VComboBox.SM: constructor()");
  1001. addDomHandler(this, LoadEvent.getType());
  1002. setScrollEnabled(true);
  1003. }
  1004. /**
  1005. * Fixes menus height to use same space as full page would use. Needed
  1006. * to avoid height changes when quickly "scrolling" to last page.
  1007. */
  1008. public void fixHeightTo(int pageItemsCount) {
  1009. setHeight(getPreferredHeight(pageItemsCount));
  1010. }
  1011. /*
  1012. * Gets the preferred height of the menu including pageItemsCount items.
  1013. */
  1014. String getPreferredHeight(int pageItemsCount) {
  1015. if (!currentSuggestions.isEmpty()) {
  1016. final int pixels = getPreferredHeight()
  1017. / currentSuggestions.size() * pageItemsCount;
  1018. return pixels + "px";
  1019. }
  1020. return "";
  1021. }
  1022. /**
  1023. * Sets the suggestions rendered in the menu.
  1024. *
  1025. * @param suggestions
  1026. * The suggestions to be rendered in the menu
  1027. */
  1028. public void setSuggestions(Collection<ComboBoxSuggestion> suggestions) {
  1029. if (enableDebug) {
  1030. debug("VComboBox.SM: setSuggestions(" + suggestions + ")");
  1031. }
  1032. clearItems();
  1033. boolean isFirstIteration = true;
  1034. for (final ComboBoxSuggestion suggestion : suggestions) {
  1035. final MenuItem mi = new MenuItem(suggestion.getDisplayString(),
  1036. true, suggestion);
  1037. String style = suggestion.getStyle();
  1038. if (style != null) {
  1039. mi.addStyleName("v-filterselect-item-" + style);
  1040. }
  1041. Roles.getListitemRole().set(mi.getElement());
  1042. WidgetUtil.sinkOnloadForImages(mi.getElement());
  1043. this.addItem(mi);
  1044. // By default, first item on the list is always highlighted,
  1045. // unless adding new items is allowed.
  1046. if (isFirstIteration && !allowNewItems) {
  1047. selectItem(mi);
  1048. }
  1049. if (currentSuggestion != null && suggestion.getOptionKey()
  1050. .equals(currentSuggestion.getOptionKey())) {
  1051. // Refresh also selected caption and icon in case they have
  1052. // been updated on the server, e.g. just the item has been
  1053. // updated, but selection (from state) has stayed the same.
  1054. // FIXME need to update selected item caption separately, if
  1055. // the selected item is not in "active data range" that is
  1056. // being sent to the client. Then this can be removed.
  1057. if (currentSuggestion.getReplacementString()
  1058. .equals(tb.getText())) {
  1059. currentSuggestion = suggestion;
  1060. selectItem(mi);
  1061. setSelectedCaption(
  1062. currentSuggestion.getReplacementString());
  1063. setSelectedItemIcon(currentSuggestion.getIconUri());
  1064. }
  1065. }
  1066. isFirstIteration = false;
  1067. }
  1068. }
  1069. /**
  1070. * Create/select a suggestion based on the used entered string. This
  1071. * method is called after filtering has completed with the given string.
  1072. *
  1073. * @param enteredItemValue
  1074. * user entered string
  1075. */
  1076. public void actOnEnteredValueAfterFiltering(String enteredItemValue) {
  1077. debug("VComboBox.SM: doPostFilterSelectedItemAction()");
  1078. final MenuItem item = getSelectedItem();
  1079. boolean handledOnServer = handledNewItem == enteredItemValue;
  1080. if (handledOnServer) {
  1081. // clear value to mark it as handled
  1082. handledNewItem = null;
  1083. }
  1084. // check for exact match in menu
  1085. int p = getItems().size();
  1086. if (p > 0) {
  1087. for (int i = 0; i < p; i++) {
  1088. final MenuItem potentialExactMatch = getItems().get(i);
  1089. if (potentialExactMatch.getText()
  1090. .equals(enteredItemValue)) {
  1091. selectItem(potentialExactMatch);
  1092. // do not send a value change event if null was and
  1093. // stays selected
  1094. if (!"".equals(enteredItemValue)
  1095. || selectedOptionKey != null
  1096. && !selectedOptionKey.isEmpty()) {
  1097. doItemAction(potentialExactMatch, true);
  1098. }
  1099. suggestionPopup.hide();
  1100. lastNewItemString = null;
  1101. connector.clearNewItemHandlingIfMatch(enteredItemValue);
  1102. return;
  1103. }
  1104. }
  1105. }
  1106. if (!handledOnServer && "".equals(enteredItemValue)
  1107. && nullSelectionAllowed) {
  1108. onNullSelected();
  1109. } else if (!handledOnServer && allowNewItems) {
  1110. if (!enteredItemValue.equals(lastNewItemString)) {
  1111. // Store last sent new item string to avoid double sends
  1112. lastNewItemString = enteredItemValue;
  1113. connector.sendNewItem(enteredItemValue);
  1114. // TODO try to select the new value if it matches what was
  1115. // sent for V7 compatibility
  1116. }
  1117. } else if (item != null && !"".equals(lastFilter)
  1118. && item.getText().toLowerCase(Locale.ROOT)
  1119. .contains(lastFilter.toLowerCase(Locale.ROOT))) {
  1120. doItemAction(item, true);
  1121. } else {
  1122. // currentSuggestion has key="" for nullselection
  1123. if (currentSuggestion != null
  1124. && !currentSuggestion.key.isEmpty()) {
  1125. // An item (not null) selected
  1126. String text = currentSuggestion.getReplacementString();
  1127. setText(text);
  1128. selectedOptionKey = currentSuggestion.key;
  1129. } else {
  1130. onNullSelected();
  1131. }
  1132. }
  1133. suggestionPopup.hide();
  1134. if (handledOnServer || !allowNewItems) {
  1135. lastNewItemString = null;
  1136. }
  1137. }
  1138. private static final String SUBPART_PREFIX = "item";
  1139. @Override
  1140. public com.google.gwt.user.client.Element getSubPartElement(
  1141. String subPart) {
  1142. int index = Integer
  1143. .parseInt(subPart.substring(SUBPART_PREFIX.length()));
  1144. MenuItem item = getItems().get(index);
  1145. return item.getElement();
  1146. }
  1147. @Override
  1148. public String getSubPartName(
  1149. com.google.gwt.user.client.Element subElement) {
  1150. if (!getElement().isOrHasChild(subElement)) {
  1151. return null;
  1152. }
  1153. Element menuItemRoot = subElement;
  1154. while (menuItemRoot != null
  1155. && !menuItemRoot.getTagName().equalsIgnoreCase("td")) {
  1156. menuItemRoot = menuItemRoot.getParentElement().cast();
  1157. }
  1158. // "menuItemRoot" is now the root of the menu item
  1159. final int itemCount = getItems().size();
  1160. for (int i = 0; i < itemCount; i++) {
  1161. if (getItems().get(i).getElement() == menuItemRoot) {
  1162. String name = SUBPART_PREFIX + i;
  1163. return name;
  1164. }
  1165. }
  1166. return null;
  1167. }
  1168. @Override
  1169. public void onLoad(LoadEvent event) {
  1170. debug("VComboBox.SM: onLoad()");
  1171. // Handle icon onload events to ensure shadow is resized
  1172. // correctly
  1173. delayedImageLoadExecutioner.trigger();
  1174. }
  1175. /**
  1176. * @deprecated use {@link SuggestionPopup#selectFirstItem()} instead.
  1177. */
  1178. @Deprecated
  1179. public void selectFirstItem() {
  1180. debug("VComboBox.SM: selectFirstItem()");
  1181. MenuItem firstItem = getItems().get(0);
  1182. selectItem(firstItem);
  1183. }
  1184. /**
  1185. * @deprecated use {@link SuggestionPopup#selectLastItem()} instead.
  1186. */
  1187. @Deprecated
  1188. public void selectLastItem() {
  1189. debug("VComboBox.SM: selectLastItem()");
  1190. List<MenuItem> items = getItems();
  1191. MenuItem lastItem = items.get(items.size() - 1);
  1192. selectItem(lastItem);
  1193. }
  1194. /*
  1195. * Gets the height of one menu item.
  1196. */
  1197. int getItemOffsetHeight() {
  1198. List<MenuItem> items = getItems();
  1199. return items != null && !items.isEmpty()
  1200. ? items.get(0).getOffsetHeight()
  1201. : 0;
  1202. }
  1203. /*
  1204. * Gets the width of one menu item.
  1205. */
  1206. int getItemOffsetWidth() {
  1207. List<MenuItem> items = getItems();
  1208. return items != null && !items.isEmpty()
  1209. ? items.get(0).getOffsetWidth()
  1210. : 0;
  1211. }
  1212. /**
  1213. * Returns true if the scroll is active on the menu element or if the
  1214. * menu currently displays the last page with less items then the
  1215. * maximum visibility (in which case the scroll is not active, but the
  1216. * scroll is active for any other page in general).
  1217. *
  1218. * @since 7.2.6
  1219. */
  1220. @Override
  1221. public boolean isScrollActive() {
  1222. String height = getElement().getStyle().getHeight();
  1223. String preferredHeight = getPreferredHeight(pageLength);
  1224. return !(height == null || height.isEmpty()
  1225. || height.equals(preferredHeight));
  1226. }
  1227. /**
  1228. * Highlight (select) an item matching the current text box content
  1229. * without triggering its action.
  1230. */
  1231. public void highlightSelectedItem() {
  1232. int p = getItems().size();
  1233. // first check if there is a key match to handle items with
  1234. // identical captions
  1235. String currentKey = currentSuggestion != null
  1236. ? currentSuggestion.getOptionKey()
  1237. : "";
  1238. for (int i = 0; i < p; i++) {
  1239. final MenuItem potentialExactMatch = getItems().get(i);
  1240. if (currentKey.equals(getSuggestionKey(potentialExactMatch))
  1241. && tb.getText().equals(potentialExactMatch.getText())) {
  1242. selectItem(potentialExactMatch);
  1243. tb.setSelectionRange(tb.getText().length(), 0);
  1244. return;
  1245. }
  1246. }
  1247. // then check for exact string match in menu
  1248. String text = tb.getText();
  1249. for (int i = 0; i < p; i++) {
  1250. final MenuItem potentialExactMatch = getItems().get(i);
  1251. if (potentialExactMatch.getText().equals(text)) {
  1252. selectItem(potentialExactMatch);
  1253. tb.setSelectionRange(tb.getText().length(), 0);
  1254. return;
  1255. }
  1256. }
  1257. }
  1258. public void markNewItemsHandled(String handledNewItem) {
  1259. this.handledNewItem = handledNewItem;
  1260. }
  1261. }
  1262. private String getSuggestionKey(MenuItem item) {
  1263. if (item != null && item.getCommand() != null) {
  1264. return ((ComboBoxSuggestion) item.getCommand()).getOptionKey();
  1265. }
  1266. return "";
  1267. }
  1268. /**
  1269. * TextBox variant used as input element for filter selects, which prevents
  1270. * selecting text when disabled.
  1271. *
  1272. * @since 7.1.5
  1273. */
  1274. public class FilterSelectTextBox extends TextBox {
  1275. /**
  1276. * Creates a new filter select text box.
  1277. *
  1278. * @since 7.6.4
  1279. */
  1280. public FilterSelectTextBox() {
  1281. /*-
  1282. * Stop the browser from showing its own suggestion popup.
  1283. *
  1284. * Using an invalid value instead of "off" as suggested by
  1285. * https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
  1286. *
  1287. * Leaving the non-standard Safari options autocapitalize and
  1288. * autocorrect untouched since those do not interfere in the same
  1289. * way, and they might be useful in a combo box where new items are
  1290. * allowed.
  1291. */
  1292. if (BrowserInfo.get().isChrome()) {
  1293. // Chrome supports "off" and random number does not work with
  1294. // Chrome
  1295. getElement().setAttribute("autocomplete", "off");
  1296. } else {
  1297. getElement().setAttribute("autocomplete", Math.random() + "");
  1298. }
  1299. }
  1300. /**
  1301. * Overridden to avoid selecting text when text input is disabled.
  1302. */
  1303. @Override
  1304. public void setSelectionRange(int pos, int length) {
  1305. if (textInputEnabled) {
  1306. /*
  1307. * set selection range with a backwards direction: anchor at the
  1308. * back, focus at the front. This means that items that are too
  1309. * long to display will display from the start and not the end
  1310. * even on Firefox.
  1311. *
  1312. * We need the JSNI function to set selection range so that we
  1313. * can use the optional direction attribute to set the anchor to
  1314. * the end and the focus to the start. This makes Firefox work
  1315. * the same way as other browsers (#13477)
  1316. */
  1317. WidgetUtil.setSelectionRange(getElement(), pos, length,
  1318. "backward");
  1319. } else {
  1320. /*
  1321. * Setting the selectionrange for an uneditable textbox leads to
  1322. * unwanted behavior when the width of the textbox is narrower
  1323. * than the width of the entry: the end of the entry is shown
  1324. * instead of the beginning. (see #13477)
  1325. *
  1326. * To avoid this, we set the caret to the beginning of the line.
  1327. */
  1328. super.setSelectionRange(0, 0);
  1329. }
  1330. }
  1331. }
  1332. /**
  1333. * Handler receiving notifications from the connector and updating the
  1334. * widget state accordingly.
  1335. *
  1336. * This class is still subject to change and should not be considered as
  1337. * public stable API.
  1338. *
  1339. * @since 8.0
  1340. */
  1341. public class DataReceivedHandler {
  1342. private Runnable navigationCallback = null;
  1343. /**
  1344. * Set true when popupopened has been clicked. Cleared on each
  1345. * UIDL-update. This handles the special case where are not filtering
  1346. * yet and the selected value has changed on the server-side. See #2119
  1347. * <p>
  1348. * For internal use only. May be removed or replaced in the future.
  1349. */
  1350. private boolean popupOpenerClicked = false;
  1351. /** For internal use only. May be removed or replaced in the future. */
  1352. private boolean waitingForFilteringResponse = false;
  1353. private boolean initialData = true;
  1354. private String pendingUserInput = null;
  1355. private boolean showPopup = false;
  1356. /**
  1357. * Called by the connector when new data for the last requested filter
  1358. * is received from the server.
  1359. */
  1360. public void dataReceived() {
  1361. if (initialData) {
  1362. suggestionPopup.menu.setSuggestions(currentSuggestions);
  1363. performSelection(serverSelectedKey, true, true);
  1364. updateSuggestionPopupMinWidth();
  1365. updateRootWidth();
  1366. initialData = false;
  1367. return;
  1368. }
  1369. suggestionPopup.menu.setSuggestions(currentSuggestions);
  1370. if (!waitingForFilteringResponse && suggestionPopup.isAttached()) {
  1371. showPopup = true;
  1372. }
  1373. // Don't show popup, if is not focused
  1374. if (showPopup && focused) {
  1375. suggestionPopup.showSuggestions(currentPage);
  1376. }
  1377. waitingForFilteringResponse = false;
  1378. if (pendingUserInput != null) {
  1379. boolean pendingHandled = suggestionPopup.menu.handledNewItem == pendingUserInput;
  1380. suggestionPopup.menu
  1381. .actOnEnteredValueAfterFiltering(pendingUserInput);
  1382. if (!allowNewItems || (pendingHandled
  1383. && suggestionPopup.menu.handledNewItem == null)) {
  1384. pendingUserInput = null;
  1385. } else {
  1386. waitingForFilteringResponse = true;
  1387. }
  1388. } else if (popupOpenerClicked) {
  1389. // make sure the current item is selected in the popup
  1390. suggestionPopup.menu.highlightSelectedItem();
  1391. } else {
  1392. navigateItemAfterPageChange();
  1393. }
  1394. if (!showPopup) {
  1395. suggestionPopup.hide();
  1396. }
  1397. popupOpenerClicked = false;
  1398. showPopup = false;
  1399. }
  1400. /**
  1401. * Perform filtering with the user entered string and when the results
  1402. * are received, perform any action appropriate for the user input
  1403. * (select an item or create a new one).
  1404. *
  1405. * @param value
  1406. * user input
  1407. */
  1408. public void reactOnInputWhenReady(String value) {
  1409. pendingUserInput = value;
  1410. showPopup = false;
  1411. filterOptions(0, value);
  1412. }
  1413. public boolean isPending(String value) {
  1414. return value != null && value.equals(pendingUserInput);
  1415. }
  1416. /*
  1417. * This method navigates to the proper item in the combobox page. This
  1418. * should be executed after setSuggestions() method which is called from
  1419. * VComboBox.showSuggestions(). ShowSuggestions() method builds the page
  1420. * content. As far as setSuggestions() method is called as deferred,
  1421. * navigateItemAfterPageChange method should be also be called as
  1422. * deferred. #11333
  1423. */
  1424. private void navigateItemAfterPageChange() {
  1425. if (navigationCallback != null) {
  1426. // navigationCallback is not reset here but after any server
  1427. // request in case you are in between two requests both changing
  1428. // the page back and forth
  1429. // we're paging w/ arrows
  1430. navigationCallback.run();
  1431. navigationCallback = null;
  1432. }
  1433. }
  1434. /**
  1435. * Called by the connector any pending navigation operations should be
  1436. * cleared.
  1437. */
  1438. public void clearPendingNavigation() {
  1439. navigationCallback = null;
  1440. }
  1441. /**
  1442. * Set a callback that is invoked when a page change occurs if there
  1443. * have not been intervening requests to the server. The callback is
  1444. * reset when any additional request is made to the server.
  1445. *
  1446. * @param callback
  1447. * method to call after filtering has completed
  1448. */
  1449. public void setNavigationCallback(Runnable callback) {
  1450. showPopup = true;
  1451. navigationCallback = callback;
  1452. }
  1453. /**
  1454. * Record that the popup opener has been clicked and the popup should be
  1455. * opened on the next request.
  1456. *
  1457. * This handles the special case where are not filtering yet and the
  1458. * selected value has changed on the server-side. See #2119. The flag is
  1459. * cleared on each server reply.
  1460. */
  1461. public void popupOpenerClicked() {
  1462. popupOpenerClicked = true;
  1463. showPopup = true;
  1464. }
  1465. /**
  1466. * Cancel a pending request to perform post-filtering actions.
  1467. */
  1468. private void cancelPendingPostFiltering() {
  1469. pendingUserInput = null;
  1470. waitingForFilteringResponse = false;
  1471. }
  1472. /**
  1473. * Called by the connector when it has finished handling any reply from
  1474. * the server, regardless of what was updated.
  1475. */
  1476. public void serverReplyHandled() {
  1477. popupOpenerClicked = false;
  1478. // if (!initDone) {
  1479. // debug("VComboBox: init done, updating widths");
  1480. // // Calculate minimum textarea width
  1481. // updateSuggestionPopupMinWidth();
  1482. // updateRootWidth();
  1483. // initDone = true;
  1484. // }
  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 a reply from the server
  1490. * with a new page of data, false otherwise
  1491. */
  1492. public boolean isWaitingForFilteringResponse() {
  1493. return waitingForFilteringResponse;
  1494. }
  1495. /**
  1496. * For internal use only - this method will be removed in the future.
  1497. *
  1498. * @return true if the combo box is waiting for initial data from the
  1499. * server, false otherwise
  1500. */
  1501. public boolean isWaitingForInitialData() {
  1502. return initialData;
  1503. }
  1504. /**
  1505. * Set a flag that filtering of options is pending a response from the
  1506. * server.
  1507. */
  1508. private void startWaitingForFilteringResponse() {
  1509. waitingForFilteringResponse = true;
  1510. }
  1511. /**
  1512. * Perform selection (if appropriate) based on a reply from the server.
  1513. * When this method is called, the suggestions have been reset if new
  1514. * ones (different from the previous list) were received from the
  1515. * server.
  1516. *
  1517. * @param selectedKey
  1518. * new selected key or null if none given by the server
  1519. * @param selectedCaption
  1520. * new selected item caption if sent by the server or null -
  1521. * this is used when the selected item is not on the current
  1522. * page
  1523. * @param selectedIconUri
  1524. * new selected item icon if sent by the server or {@ code
  1525. * null} to clear
  1526. */
  1527. public void updateSelectionFromServer(String selectedKey,
  1528. String selectedCaption, String selectedIconUri) {
  1529. boolean oldSuggestionTextMatchTheOldSelection = currentSuggestion != null
  1530. && currentSuggestion.getReplacementString()
  1531. .equals(tb.getText());
  1532. serverSelectedKey = selectedKey;
  1533. performSelection(selectedKey, oldSuggestionTextMatchTheOldSelection,
  1534. !isWaitingForFilteringResponse() || popupOpenerClicked);
  1535. // currentSuggestion should be set to match the value of the
  1536. // ComboBox
  1537. resetCurrentSuggestionBasedOnServerResponse(selectedKey,
  1538. selectedCaption, selectedIconUri);
  1539. cancelPendingPostFiltering();
  1540. setSelectedCaption(selectedCaption);
  1541. setSelectedItemIcon(selectedIconUri);
  1542. }
  1543. /*
  1544. * Updates the current suggestion based on values provided by the
  1545. * server.
  1546. */
  1547. private void resetCurrentSuggestionBasedOnServerResponse(
  1548. String selectedKey, String selectedCaption,
  1549. String selectedIconUri) {
  1550. if (currentSuggestion == null
  1551. && (selectedKey != null || selectedCaption != null)) {
  1552. currentSuggestion = new ComboBoxSuggestion(selectedKey,
  1553. selectedCaption, "", selectedIconUri);
  1554. } else if (selectedKey == null && selectedCaption == null) {
  1555. currentSuggestion = null;
  1556. }
  1557. }
  1558. }
  1559. // TODO decide whether this should change - affects themes and v7
  1560. public static final String CLASSNAME = "v-filterselect";
  1561. private static final String STYLE_NO_INPUT = "no-input";
  1562. /** For internal use only. May be removed or replaced in the future. */
  1563. public int pageLength = 10;
  1564. private boolean enableDebug = false;
  1565. private final FlowPanel panel = new FlowPanel();
  1566. /**
  1567. * The text box where the filter is written
  1568. * <p>
  1569. * For internal use only. May be removed or replaced in the future.
  1570. */
  1571. public final TextBox tb;
  1572. /** For internal use only. May be removed or replaced in the future. */
  1573. public final SuggestionPopup suggestionPopup;
  1574. /**
  1575. * Used when measuring the width of the popup
  1576. */
  1577. private final HTML popupOpener = new HTML("");
  1578. private class IconWidget extends Widget {
  1579. IconWidget(Icon icon) {
  1580. setElement(icon.getElement());
  1581. }
  1582. }
  1583. private IconWidget selectedItemIcon;
  1584. /** For internal use only. May be removed or replaced in the future. */
  1585. public ComboBoxConnector connector;
  1586. /** For internal use only. May be removed or replaced in the future. */
  1587. public int currentPage;
  1588. /**
  1589. * A collection of available suggestions (options) as received from the
  1590. * server.
  1591. * <p>
  1592. * For internal use only. May be removed or replaced in the future.
  1593. */
  1594. public final List<ComboBoxSuggestion> currentSuggestions = new ArrayList<>();
  1595. /** For internal use only. May be removed or replaced in the future. */
  1596. public String serverSelectedKey;
  1597. /** For internal use only. May be removed or replaced in the future. */
  1598. public String selectedOptionKey;
  1599. /** For internal use only. May be removed or replaced in the future. */
  1600. public boolean initDone = false;
  1601. /**
  1602. * For internal use only. May be removed or replaced in the future.
  1603. */
  1604. public String lastFilter = "";
  1605. /**
  1606. * The current suggestion selected from the dropdown. This is one of the
  1607. * values in currentSuggestions except when filtering, in this case
  1608. * currentSuggestion might not be in currentSuggestions.
  1609. * <p>
  1610. * For internal use only. May be removed or replaced in the future.
  1611. */
  1612. public ComboBoxSuggestion currentSuggestion;
  1613. /** For internal use only. May be removed or replaced in the future. */
  1614. public boolean allowNewItems;
  1615. /** Total number of suggestions, excluding null selection item. */
  1616. private int totalSuggestions;
  1617. /** For internal use only. May be removed or replaced in the future. */
  1618. public boolean nullSelectionAllowed;
  1619. /** For internal use only. May be removed or replaced in the future. */
  1620. public boolean nullSelectItem;
  1621. /** For internal use only. May be removed or replaced in the future. */
  1622. public boolean enabled;
  1623. /** For internal use only. May be removed or replaced in the future. */
  1624. public boolean readonly;
  1625. /** For internal use only. May be removed or replaced in the future. */
  1626. public String inputPrompt = "";
  1627. /** For internal use only. May be removed or replaced in the future. */
  1628. public int suggestionPopupMinWidth = 0;
  1629. public String suggestionPopupWidth = null;
  1630. private int popupWidth = -1;
  1631. /**
  1632. * Stores the last new item string to avoid double submissions. Cleared on
  1633. * uidl updates.
  1634. * <p>
  1635. * For internal use only. May be removed or replaced in the future.
  1636. */
  1637. public String lastNewItemString;
  1638. /** For internal use only. May be removed or replaced in the future. */
  1639. public boolean focused = false;
  1640. /** For internal use only. May be removed or replaced in the future. */
  1641. public boolean noKeyDownEvents = true;
  1642. /**
  1643. * If set to false, the component should not allow entering text to the
  1644. * field even for filtering.
  1645. */
  1646. private boolean textInputEnabled = true;
  1647. private String emptySelectionCaption = "";
  1648. private final DataReceivedHandler dataReceivedHandler = new DataReceivedHandler();
  1649. /**
  1650. * Default constructor.
  1651. */
  1652. public VComboBox() {
  1653. tb = createTextBox();
  1654. suggestionPopup = createSuggestionPopup();
  1655. popupOpener.addMouseDownHandler(VComboBox.this);
  1656. Roles.getButtonRole().setAriaHiddenState(popupOpener.getElement(),
  1657. true);
  1658. Roles.getButtonRole().set(popupOpener.getElement());
  1659. panel.add(tb);
  1660. panel.add(popupOpener);
  1661. initWidget(panel);
  1662. Roles.getComboboxRole().set(panel.getElement());
  1663. tb.addKeyDownHandler(this);
  1664. tb.addKeyUpHandler(this);
  1665. tb.addFocusHandler(this);
  1666. tb.addBlurHandler(this);
  1667. panel.addDomHandler(this, ClickEvent.getType());
  1668. setStyleName(CLASSNAME);
  1669. sinkEvents(Event.ONPASTE);
  1670. }
  1671. private static double getMarginBorderPaddingWidth(Element element) {
  1672. final ComputedStyle s = new ComputedStyle(element);
  1673. return s.getMarginWidth() + s.getBorderWidth() + s.getPaddingWidth();
  1674. }
  1675. /**
  1676. * This method will reset the saved item string which is added last time.
  1677. */
  1678. public void resetLastNewItemString() {
  1679. // Clean the temp string eagerly in order to re-add the same value again
  1680. // after data provider got reset.
  1681. // Fixes issue https://github.com/vaadin/framework/issues/11317
  1682. lastNewItemString = null;
  1683. }
  1684. /*
  1685. * (non-Javadoc)
  1686. *
  1687. * @see
  1688. * com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt
  1689. * .user.client.Event)
  1690. */
  1691. @Override
  1692. public void onBrowserEvent(Event event) {
  1693. super.onBrowserEvent(event);
  1694. if (event.getTypeInt() == Event.ONPASTE) {
  1695. if (textInputEnabled && connector.isEnabled()
  1696. && !connector.isReadOnly()) {
  1697. Scheduler.get()
  1698. .scheduleDeferred(() -> filterOptions(currentPage));
  1699. }
  1700. }
  1701. }
  1702. /**
  1703. * This method will create the TextBox used by the VComboBox instance. It is
  1704. * invoked during the Constructor and should only be overridden if a custom
  1705. * TextBox shall be used. The overriding method cannot use any instance
  1706. * variables.
  1707. *
  1708. * @since 7.1.5
  1709. * @return TextBox instance used by this VComboBox
  1710. */
  1711. protected TextBox createTextBox() {
  1712. return new FilterSelectTextBox();
  1713. }
  1714. /**
  1715. * This method will create the SuggestionPopup used by the VComboBox
  1716. * instance. It is invoked during the Constructor and should only be
  1717. * overridden if a custom SuggestionPopup shall be used. The overriding
  1718. * method cannot use any instance variables.
  1719. *
  1720. * @since 7.1.5
  1721. * @return SuggestionPopup instance used by this VComboBox
  1722. */
  1723. protected SuggestionPopup createSuggestionPopup() {
  1724. return new SuggestionPopup();
  1725. }
  1726. @Override
  1727. public void setStyleName(String style) {
  1728. super.setStyleName(style);
  1729. updateStyleNames();
  1730. }
  1731. @Override
  1732. public void setStylePrimaryName(String style) {
  1733. super.setStylePrimaryName(style);
  1734. updateStyleNames();
  1735. }
  1736. protected void updateStyleNames() {
  1737. tb.setStyleName(getStylePrimaryName() + "-input");
  1738. popupOpener.setStyleName(getStylePrimaryName() + "-button");
  1739. suggestionPopup.setStyleName(getStylePrimaryName() + "-suggestpopup");
  1740. }
  1741. /**
  1742. * Does the Select have more pages?
  1743. *
  1744. * @return true if a next page exists, else false if the current page is the
  1745. * last page
  1746. */
  1747. public boolean hasNextPage() {
  1748. return pageLength > 0
  1749. && getTotalSuggestionsIncludingNullSelectionItem() > (currentPage
  1750. + 1) * pageLength;
  1751. }
  1752. /**
  1753. * Filters the options at a certain page. Uses the text box input as a
  1754. * filter and ensures the popup is opened when filtering results are
  1755. * available.
  1756. *
  1757. * @param page
  1758. * The page which items are to be filtered
  1759. */
  1760. public void filterOptions(int page) {
  1761. dataReceivedHandler.popupOpenerClicked();
  1762. filterOptions(page, tb.getText());
  1763. }
  1764. /**
  1765. * Filters the options at certain page using the given filter.
  1766. *
  1767. * @param page
  1768. * The page to filter
  1769. * @param filter
  1770. * The filter to apply to the components
  1771. */
  1772. public void filterOptions(int page, String filter) {
  1773. debug("VComboBox: filterOptions(" + page + ", " + filter + ")");
  1774. if (filter.equals(lastFilter) && currentPage == page
  1775. && suggestionPopup.isAttached()) {
  1776. // already have the page
  1777. dataReceivedHandler.dataReceived();
  1778. return;
  1779. }
  1780. if (!filter.equals(lastFilter)) {
  1781. // when filtering, let the server decide the page unless we've
  1782. // set the filter to empty and explicitly said that we want to see
  1783. // the results starting from page 0.
  1784. if (filter.isEmpty() && page != 0) {
  1785. // let server decide
  1786. page = -1;
  1787. } else {
  1788. page = 0;
  1789. }
  1790. }
  1791. dataReceivedHandler.startWaitingForFilteringResponse();
  1792. connector.requestPage(page, filter);
  1793. lastFilter = filter;
  1794. // If the data was updated from cache, the page has been updated too, if
  1795. // not, update
  1796. if (dataReceivedHandler.isWaitingForFilteringResponse()) {
  1797. currentPage = page;
  1798. }
  1799. }
  1800. /** For internal use only. May be removed or replaced in the future. */
  1801. public void updateReadOnly() {
  1802. debug("VComboBox: updateReadOnly()");
  1803. tb.setReadOnly(readonly || !textInputEnabled);
  1804. }
  1805. public void setTextInputAllowed(boolean textInputAllowed) {
  1806. debug("VComboBox: setTextInputAllowed()");
  1807. // Always update styles as they might have been overwritten
  1808. if (textInputAllowed) {
  1809. removeStyleDependentName(STYLE_NO_INPUT);
  1810. Roles.getTextboxRole().removeAriaReadonlyProperty(tb.getElement());
  1811. } else {
  1812. addStyleDependentName(STYLE_NO_INPUT);
  1813. Roles.getTextboxRole().setAriaReadonlyProperty(tb.getElement(),
  1814. true);
  1815. }
  1816. if (textInputEnabled != textInputAllowed) {
  1817. textInputEnabled = textInputAllowed;
  1818. updateReadOnly();
  1819. }
  1820. }
  1821. /**
  1822. * Sets the text in the text box.
  1823. *
  1824. * @param text
  1825. * the text to set in the text box
  1826. */
  1827. public void setText(final String text) {
  1828. /**
  1829. * To leave caret in the beginning of the line. SetSelectionRange
  1830. * wouldn't work on IE (see #13477)
  1831. */
  1832. Direction previousDirection = tb.getDirection();
  1833. tb.setDirection(Direction.RTL);
  1834. tb.setText(text);
  1835. tb.setDirection(previousDirection);
  1836. }
  1837. /**
  1838. * Set or reset the placeholder attribute for the text field.
  1839. *
  1840. * @param placeholder
  1841. * new placeholder string or null for none
  1842. */
  1843. public void setPlaceholder(String placeholder) {
  1844. inputPrompt = placeholder;
  1845. updatePlaceholder();
  1846. }
  1847. /**
  1848. * Update placeholder visibility (hidden when read-only or disabled).
  1849. */
  1850. public void updatePlaceholder() {
  1851. if (inputPrompt != null && enabled && !readonly) {
  1852. tb.getElement().setAttribute("placeholder", inputPrompt);
  1853. } else {
  1854. tb.getElement().removeAttribute("placeholder");
  1855. }
  1856. }
  1857. /**
  1858. * Triggered when a suggestion is selected.
  1859. *
  1860. * @param suggestion
  1861. * The suggestion that just got selected.
  1862. */
  1863. public void onSuggestionSelected(ComboBoxSuggestion suggestion) {
  1864. if (enableDebug) {
  1865. debug("VComboBox: onSuggestionSelected(" + suggestion.caption + ": "
  1866. + suggestion.key + ")");
  1867. }
  1868. // special handling of null selection
  1869. if (suggestion.key.isEmpty()) {
  1870. onNullSelected();
  1871. return;
  1872. }
  1873. dataReceivedHandler.cancelPendingPostFiltering();
  1874. currentSuggestion = suggestion;
  1875. String newKey = suggestion.getOptionKey();
  1876. String text = suggestion.getReplacementString();
  1877. setText(text);
  1878. setSelectedItemIcon(suggestion.getIconUri());
  1879. if (!newKey.equals(selectedOptionKey)) {
  1880. selectedOptionKey = newKey;
  1881. connector.sendSelection(selectedOptionKey);
  1882. setSelectedCaption(text);
  1883. // currentPage = -1; // forget the page
  1884. }
  1885. suggestionPopup.hide();
  1886. }
  1887. /**
  1888. * Triggered when an empty value is selected and null selection is allowed.
  1889. */
  1890. public void onNullSelected() {
  1891. if (enableDebug) {
  1892. debug("VComboBox: onNullSelected()");
  1893. }
  1894. dataReceivedHandler.cancelPendingPostFiltering();
  1895. currentSuggestion = null;
  1896. setText(getEmptySelectionCaption());
  1897. setSelectedItemIcon(null);
  1898. if (!"".equals(selectedOptionKey) || selectedOptionKey != null) {
  1899. selectedOptionKey = "";
  1900. setSelectedCaption("");
  1901. connector.sendSelection(null);
  1902. // currentPage = 0;
  1903. }
  1904. updatePlaceholder();
  1905. suggestionPopup.hide();
  1906. }
  1907. /**
  1908. * Sets the icon URI of the selected item. The icon is shown on the left
  1909. * side of the item caption text. Set the URI to null to remove the icon.
  1910. *
  1911. * @param iconUri
  1912. * The URI of the icon, or null to remove icon
  1913. */
  1914. public void setSelectedItemIcon(String iconUri) {
  1915. if (selectedItemIcon != null) {
  1916. panel.remove(selectedItemIcon);
  1917. }
  1918. if (iconUri == null || iconUri.isEmpty()) {
  1919. if (selectedItemIcon != null) {
  1920. selectedItemIcon = null;
  1921. afterSelectedItemIconChange();
  1922. }
  1923. } else {
  1924. selectedItemIcon = new IconWidget(
  1925. connector.getConnection().getIcon(iconUri));
  1926. selectedItemIcon.addDomHandler(VComboBox.this,
  1927. ClickEvent.getType());
  1928. selectedItemIcon.addDomHandler(VComboBox.this,
  1929. MouseDownEvent.getType());
  1930. selectedItemIcon.addDomHandler(
  1931. event -> afterSelectedItemIconChange(),
  1932. LoadEvent.getType());
  1933. panel.insert(selectedItemIcon, 0);
  1934. afterSelectedItemIconChange();
  1935. }
  1936. }
  1937. private void afterSelectedItemIconChange() {
  1938. if (BrowserInfo.get().isWebkit()) {
  1939. // Some browsers need a nudge to reposition the text field
  1940. forceReflow();
  1941. }
  1942. updateRootWidth();
  1943. if (selectedItemIcon != null) {
  1944. updateSelectedIconPosition();
  1945. }
  1946. }
  1947. /**
  1948. * Perform selection based on a message from the server.
  1949. *
  1950. * The special case where the selected item is not on the current page is
  1951. * handled separately by the caller.
  1952. *
  1953. * @param selectedKey
  1954. * non-empty selected item key
  1955. * @param forceUpdateText
  1956. * true to force the text box value to match the suggestion text
  1957. * @param updatePromptAndSelectionIfMatchFound
  1958. */
  1959. private void performSelection(String selectedKey, boolean forceUpdateText,
  1960. boolean updatePromptAndSelectionIfMatchFound) {
  1961. if (selectedKey == null || selectedKey.isEmpty()) {
  1962. currentSuggestion = null; // #13217
  1963. selectedOptionKey = null;
  1964. setText(getEmptySelectionCaption());
  1965. }
  1966. // some item selected
  1967. for (ComboBoxSuggestion suggestion : currentSuggestions) {
  1968. String suggestionKey = suggestion.getOptionKey();
  1969. if (!suggestionKey.equals(selectedKey)) {
  1970. continue;
  1971. }
  1972. // at this point, suggestion key matches the new selection key
  1973. if (updatePromptAndSelectionIfMatchFound) {
  1974. if (!suggestionKey.equals(selectedOptionKey) || suggestion
  1975. .getReplacementString().equals(tb.getText())
  1976. || forceUpdateText) {
  1977. // Update text field if we've got a new
  1978. // selection
  1979. // Also update if we've got the same text to
  1980. // retain old text selection behavior
  1981. // OR if selected item caption is changed.
  1982. setText(suggestion.getReplacementString());
  1983. selectedOptionKey = suggestionKey;
  1984. }
  1985. }
  1986. currentSuggestion = suggestion;
  1987. // only a single item can be selected
  1988. break;
  1989. }
  1990. }
  1991. private void forceReflow() {
  1992. WidgetUtil.setStyleTemporarily(tb.getElement(), "zoom", "1");
  1993. }
  1994. /**
  1995. * Positions the icon vertically in the middle. Should be called after the
  1996. * icon has loaded
  1997. */
  1998. private void updateSelectedIconPosition() {
  1999. // Position icon vertically to middle
  2000. int availableHeight = 0;
  2001. availableHeight = getOffsetHeight();
  2002. int iconHeight = WidgetUtil.getRequiredHeight(selectedItemIcon);
  2003. int marginTop = (availableHeight - iconHeight) / 2;
  2004. selectedItemIcon.getElement().getStyle().setMarginTop(marginTop,
  2005. Unit.PX);
  2006. }
  2007. private static Set<Integer> navigationKeyCodes = new HashSet<>();
  2008. static {
  2009. navigationKeyCodes.add(KeyCodes.KEY_DOWN);
  2010. navigationKeyCodes.add(KeyCodes.KEY_UP);
  2011. navigationKeyCodes.add(KeyCodes.KEY_PAGEDOWN);
  2012. navigationKeyCodes.add(KeyCodes.KEY_PAGEUP);
  2013. navigationKeyCodes.add(KeyCodes.KEY_ENTER);
  2014. }
  2015. /*
  2016. * (non-Javadoc)
  2017. *
  2018. * @see
  2019. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  2020. * .event.dom.client.KeyDownEvent)
  2021. */
  2022. @Override
  2023. public void onKeyDown(KeyDownEvent event) {
  2024. if (enabled && !readonly) {
  2025. int keyCode = event.getNativeKeyCode();
  2026. if (enableDebug) {
  2027. debug("VComboBox: key down: " + keyCode);
  2028. }
  2029. if (dataReceivedHandler.isWaitingForFilteringResponse()
  2030. && navigationKeyCodes.contains(keyCode)
  2031. && (!allowNewItems || keyCode != KeyCodes.KEY_ENTER)) {
  2032. /*
  2033. * Keyboard navigation events should not be handled while we are
  2034. * waiting for a response. This avoids flickering, disappearing
  2035. * items, wrongly interpreted responses and more.
  2036. */
  2037. if (enableDebug) {
  2038. debug("Ignoring " + keyCode
  2039. + " because we are waiting for a filtering response");
  2040. }
  2041. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2042. event.stopPropagation();
  2043. return;
  2044. }
  2045. noKeyDownEvents = false;
  2046. if (suggestionPopup.isAttached()) {
  2047. if (enableDebug) {
  2048. debug("Keycode " + keyCode + " target is popup");
  2049. }
  2050. popupKeyDown(event);
  2051. } else {
  2052. if (enableDebug) {
  2053. debug("Keycode " + keyCode + " target is text field");
  2054. }
  2055. inputFieldKeyDown(event);
  2056. }
  2057. }
  2058. }
  2059. private void debug(String string) {
  2060. if (enableDebug) {
  2061. getLogger().severe(string);
  2062. }
  2063. }
  2064. /**
  2065. * Triggered when a key is pressed in the text box
  2066. *
  2067. * @param event
  2068. * The KeyDownEvent
  2069. */
  2070. private void inputFieldKeyDown(KeyDownEvent event) {
  2071. if (enableDebug) {
  2072. debug("VComboBox: inputFieldKeyDown(" + event.getNativeKeyCode()
  2073. + ")");
  2074. }
  2075. switch (event.getNativeKeyCode()) {
  2076. case KeyCodes.KEY_DOWN:
  2077. case KeyCodes.KEY_UP:
  2078. case KeyCodes.KEY_PAGEDOWN:
  2079. case KeyCodes.KEY_PAGEUP:
  2080. // open popup as from gadget
  2081. filterOptions(-1, "");
  2082. tb.selectAll();
  2083. dataReceivedHandler.popupOpenerClicked();
  2084. break;
  2085. case KeyCodes.KEY_ENTER:
  2086. /*
  2087. * This only handles the case when new items is allowed, a text is
  2088. * entered, the popup opener button is clicked to close the popup
  2089. * and enter is then pressed (see #7560).
  2090. */
  2091. if (!allowNewItems) {
  2092. return;
  2093. }
  2094. if (currentSuggestion != null && tb.getText()
  2095. .equals(currentSuggestion.getReplacementString())) {
  2096. // Retain behavior from #6686 by returning without stopping
  2097. // propagation if there's nothing to do
  2098. return;
  2099. }
  2100. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  2101. suggestionPopup.hide();
  2102. event.stopPropagation();
  2103. break;
  2104. }
  2105. }
  2106. /**
  2107. * Triggered when a key was pressed in the suggestion popup.
  2108. *
  2109. * @param event
  2110. * The KeyDownEvent of the key
  2111. */
  2112. private void popupKeyDown(KeyDownEvent event) {
  2113. if (enableDebug) {
  2114. debug("VComboBox: popupKeyDown(" + event.getNativeKeyCode() + ")");
  2115. }
  2116. // Propagation of handled events is stopped so other handlers such as
  2117. // shortcut key handlers do not also handle the same events.
  2118. switch (event.getNativeKeyCode()) {
  2119. case KeyCodes.KEY_DOWN:
  2120. suggestionPopup.selectNextItem();
  2121. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2122. event.stopPropagation();
  2123. break;
  2124. case KeyCodes.KEY_UP:
  2125. suggestionPopup.selectPrevItem();
  2126. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2127. event.stopPropagation();
  2128. break;
  2129. case KeyCodes.KEY_PAGEDOWN:
  2130. selectNextPage();
  2131. event.stopPropagation();
  2132. break;
  2133. case KeyCodes.KEY_PAGEUP:
  2134. selectPrevPage();
  2135. event.stopPropagation();
  2136. break;
  2137. case KeyCodes.KEY_ESCAPE:
  2138. reset();
  2139. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2140. event.stopPropagation();
  2141. break;
  2142. case KeyCodes.KEY_TAB:
  2143. case KeyCodes.KEY_ENTER:
  2144. // queue this, may be cancelled by selection
  2145. int selectedIndex = suggestionPopup.menu.getSelectedIndex();
  2146. if (!allowNewItems && selectedIndex != -1
  2147. && !currentSuggestions.isEmpty()) {
  2148. onSuggestionSelected(currentSuggestions.get(selectedIndex));
  2149. } else {
  2150. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  2151. }
  2152. suggestionPopup.hide();
  2153. event.stopPropagation();
  2154. break;
  2155. }
  2156. }
  2157. /*
  2158. * Show the prev page.
  2159. */
  2160. private void selectPrevPage() {
  2161. if (currentPage > 0) {
  2162. dataReceivedHandler.setNavigationCallback(
  2163. () -> suggestionPopup.selectLastItem());
  2164. filterOptions(currentPage - 1, lastFilter);
  2165. }
  2166. }
  2167. /*
  2168. * Show the next page.
  2169. */
  2170. private void selectNextPage() {
  2171. if (hasNextPage()) {
  2172. dataReceivedHandler.setNavigationCallback(
  2173. () -> suggestionPopup.selectFirstItem());
  2174. filterOptions(currentPage + 1, lastFilter);
  2175. }
  2176. }
  2177. /**
  2178. * Triggered when a key was depressed.
  2179. *
  2180. * @param event
  2181. * The KeyUpEvent of the key depressed
  2182. */
  2183. @Override
  2184. public void onKeyUp(KeyUpEvent event) {
  2185. if (enableDebug) {
  2186. debug("VComboBox: onKeyUp(" + event.getNativeKeyCode() + ")");
  2187. }
  2188. if (enabled && !readonly) {
  2189. switch (event.getNativeKeyCode()) {
  2190. case KeyCodes.KEY_ENTER:
  2191. case KeyCodes.KEY_TAB:
  2192. case KeyCodes.KEY_SHIFT:
  2193. case KeyCodes.KEY_CTRL:
  2194. case KeyCodes.KEY_ALT:
  2195. case KeyCodes.KEY_DOWN:
  2196. case KeyCodes.KEY_UP:
  2197. case KeyCodes.KEY_RIGHT:
  2198. case KeyCodes.KEY_LEFT:
  2199. case KeyCodes.KEY_PAGEDOWN:
  2200. case KeyCodes.KEY_PAGEUP:
  2201. case KeyCodes.KEY_ESCAPE:
  2202. case KeyCodes.KEY_HOME:
  2203. case KeyCodes.KEY_END:
  2204. // NOP
  2205. break;
  2206. default:
  2207. if (textInputEnabled && !noKeyDownEvents) {
  2208. // when filtering, we always want to see the results on the
  2209. // first page first.
  2210. filterOptions(0);
  2211. }
  2212. break;
  2213. }
  2214. }
  2215. }
  2216. /**
  2217. * Resets the ComboBox to its initial state.
  2218. */
  2219. private void reset() {
  2220. debug("VComboBox: reset()");
  2221. // just fetch selected information from state
  2222. String text = connector.getState().selectedItemCaption;
  2223. setText(text == null ? getEmptySelectionCaption() : text);
  2224. setSelectedItemIcon(connector.getState().selectedItemIcon);
  2225. selectedOptionKey = (connector.getState().selectedItemKey);
  2226. if (selectedOptionKey == null || selectedOptionKey.isEmpty()) {
  2227. currentSuggestion = null; // #13217
  2228. selectedOptionKey = null;
  2229. updatePlaceholder();
  2230. } else {
  2231. currentSuggestion = currentSuggestions.stream()
  2232. .filter(suggestion -> suggestion.getOptionKey()
  2233. .equals(selectedOptionKey))
  2234. .findAny().orElse(null);
  2235. }
  2236. suggestionPopup.hide();
  2237. }
  2238. /**
  2239. * Listener for popupopener.
  2240. */
  2241. @Override
  2242. public void onClick(ClickEvent event) {
  2243. debug("VComboBox: onClick()");
  2244. if (textInputEnabled && event.getNativeEvent().getEventTarget()
  2245. .cast() == tb.getElement()) {
  2246. // Don't process clicks on the text field if text input is enabled
  2247. return;
  2248. }
  2249. if (enabled && !readonly) {
  2250. // ask suggestionPopup if it was just closed, we are using GWT
  2251. // Popup's auto close feature
  2252. if (!suggestionPopup.isJustClosed()) {
  2253. filterOptions(-1, "");
  2254. dataReceivedHandler.popupOpenerClicked();
  2255. }
  2256. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2257. focus();
  2258. tb.selectAll();
  2259. }
  2260. }
  2261. /**
  2262. * Update minimum width for combo box textarea based on input prompt and
  2263. * suggestions.
  2264. * <p>
  2265. * For internal use only. May be removed or replaced in the future.
  2266. */
  2267. public void updateSuggestionPopupMinWidth() {
  2268. debug("VComboBox: updateSuggestionPopupMinWidth()");
  2269. // used only to calculate minimum width
  2270. String captions = WidgetUtil.escapeHTML(inputPrompt);
  2271. for (ComboBoxSuggestion suggestion : currentSuggestions) {
  2272. // Collect captions so we can calculate minimum width for
  2273. // textarea
  2274. if (!captions.isEmpty()) {
  2275. captions += "|";
  2276. }
  2277. captions += WidgetUtil
  2278. .escapeHTML(suggestion.getReplacementString());
  2279. }
  2280. // Calculate minimum textarea width
  2281. suggestionPopupMinWidth = minWidth(captions);
  2282. }
  2283. /**
  2284. * Calculate minimum width for FilterSelect textarea.
  2285. * <p>
  2286. * For internal use only. May be removed or replaced in the future.
  2287. *
  2288. * @param captions
  2289. * pipe separated string listing all the captions to measure
  2290. * @return minimum width in pixels
  2291. */
  2292. public native int minWidth(String captions)
  2293. /*-{
  2294. if (!captions || captions.length <= 0)
  2295. return 0;
  2296. captions = captions.split("|");
  2297. var d = $wnd.document.createElement("div");
  2298. var html = "";
  2299. for (var i=0; i < captions.length; i++) {
  2300. html += "<div>" + captions[i] + "</div>";
  2301. // TODO apply same CSS classname as in suggestionmenu
  2302. }
  2303. d.style.position = "absolute";
  2304. d.style.top = "0";
  2305. d.style.left = "0";
  2306. d.style.visibility = "hidden";
  2307. d.innerHTML = html;
  2308. $wnd.document.body.appendChild(d);
  2309. var w = d.offsetWidth;
  2310. $wnd.document.body.removeChild(d);
  2311. return w;
  2312. }-*/;
  2313. /**
  2314. * A flag which prevents a focus event from taking place.
  2315. */
  2316. boolean iePreventNextFocus = false;
  2317. /*
  2318. * (non-Javadoc)
  2319. *
  2320. * @see
  2321. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  2322. * .dom.client.FocusEvent)
  2323. */
  2324. @Override
  2325. public void onFocus(FocusEvent event) {
  2326. debug("VComboBox: onFocus()");
  2327. /*
  2328. * When we disable a blur event in ie we need to refocus the textfield.
  2329. * This will cause a focus event we do not want to process, so in that
  2330. * case we just ignore it.
  2331. */
  2332. if (BrowserInfo.get().isIE() && iePreventNextFocus) {
  2333. iePreventNextFocus = false;
  2334. return;
  2335. }
  2336. noKeyDownEvents = true;
  2337. focused = true;
  2338. updatePlaceholder();
  2339. addStyleDependentName("focus");
  2340. connector.sendFocusEvent();
  2341. connector.getConnection().getVTooltip()
  2342. .showAssistive(connector.getTooltipInfo(getElement()));
  2343. }
  2344. /**
  2345. * A flag which cancels the blur event and sets the focus back to the
  2346. * textfield if the Browser is IE.
  2347. */
  2348. boolean preventNextBlurEventInIE = false;
  2349. private String explicitSelectedCaption;
  2350. /*
  2351. * (non-Javadoc)
  2352. *
  2353. * @see
  2354. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  2355. * .dom.client.BlurEvent)
  2356. */
  2357. @Override
  2358. public void onBlur(BlurEvent event) {
  2359. debug("VComboBox: onBlur()");
  2360. if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) {
  2361. /*
  2362. * Clicking in the suggestion popup or on the popup button in IE
  2363. * causes a blur event to be sent for the field. In other browsers
  2364. * this is prevented by canceling/preventing default behavior for
  2365. * the focus event, in IE we handle it here by refocusing the text
  2366. * field and ignoring the resulting focus event for the textfield
  2367. * (in onFocus).
  2368. */
  2369. preventNextBlurEventInIE = false;
  2370. Element focusedElement = WidgetUtil.getFocusedElement();
  2371. if (getElement().isOrHasChild(focusedElement) || suggestionPopup
  2372. .getElement().isOrHasChild(focusedElement)) {
  2373. // IF the suggestion popup or another part of the VComboBox
  2374. // was focused, move the focus back to the textfield and prevent
  2375. // the triggered focus event (in onFocus).
  2376. iePreventNextFocus = true;
  2377. tb.setFocus(true);
  2378. return;
  2379. }
  2380. }
  2381. focused = false;
  2382. updatePlaceholder();
  2383. removeStyleDependentName("focus");
  2384. // Send new items when clicking out with the mouse.
  2385. if (!readonly) {
  2386. if (textInputEnabled && allowNewItems
  2387. && (currentSuggestion == null || !tb.getText().equals(
  2388. currentSuggestion.getReplacementString()))) {
  2389. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  2390. } else {
  2391. reset();
  2392. }
  2393. suggestionPopup.hide();
  2394. }
  2395. connector.sendBlurEvent();
  2396. }
  2397. /*
  2398. * (non-Javadoc)
  2399. *
  2400. * @see com.vaadin.client.Focusable#focus()
  2401. */
  2402. @Override
  2403. public void focus() {
  2404. debug("VComboBox: focus()");
  2405. focused = true;
  2406. updatePlaceholder();
  2407. tb.setFocus(true);
  2408. }
  2409. /**
  2410. * Calculates the width of the select if the select has undefined width.
  2411. * Should be called when the width changes or when the icon changes.
  2412. * <p>
  2413. * For internal use only. May be removed or replaced in the future.
  2414. */
  2415. public void updateRootWidth() {
  2416. debug("VComboBox: updateRootWidth()");
  2417. if (connector.isUndefinedWidth()) {
  2418. /*
  2419. * When the select has a undefined with we need to check that we are
  2420. * only setting the text box width relative to the first page width
  2421. * of the items. If this is not done the text box width will change
  2422. * when the popup is used to view longer items than the text box is
  2423. * wide.
  2424. */
  2425. int w = WidgetUtil.getRequiredWidth(this);
  2426. if (dataReceivedHandler.isWaitingForInitialData()
  2427. && suggestionPopupMinWidth > w) {
  2428. /*
  2429. * We want to compensate for the paddings just to preserve the
  2430. * exact size as in Vaadin 6.x, but we get here before
  2431. * MeasuredSize has been initialized.
  2432. * Util.measureHorizontalPaddingAndBorder does not work with
  2433. * border-box, so we must do this the hard way.
  2434. */
  2435. Style style = getElement().getStyle();
  2436. String originalPadding = style.getPadding();
  2437. String originalBorder = style.getBorderWidth();
  2438. style.setPaddingLeft(0, Unit.PX);
  2439. style.setBorderWidth(0, Unit.PX);
  2440. style.setProperty("padding", originalPadding);
  2441. style.setProperty("borderWidth", originalBorder);
  2442. // Use util.getRequiredWidth instead of getOffsetWidth here
  2443. int iconWidth = selectedItemIcon == null ? 0
  2444. : WidgetUtil.getRequiredWidth(selectedItemIcon);
  2445. int buttonWidth = popupOpener == null ? 0
  2446. : WidgetUtil.getRequiredWidth(popupOpener);
  2447. /*
  2448. * Instead of setting the width of the wrapper, set the width of
  2449. * the combobox. Subtract the width of the icon and the
  2450. * popupopener
  2451. */
  2452. tb.setWidth(suggestionPopupMinWidth - iconWidth - buttonWidth
  2453. + "px");
  2454. }
  2455. /*
  2456. * Lock the textbox width to its current value if it's not already
  2457. * locked. This can happen after setWidth("") which resets the
  2458. * textbox width to "100%".
  2459. */
  2460. if (!tb.getElement().getStyle().getWidth().endsWith("px")) {
  2461. int iconWidth = selectedItemIcon == null ? 0
  2462. : selectedItemIcon.getOffsetWidth();
  2463. tb.setWidth(tb.getOffsetWidth() - iconWidth + "px");
  2464. }
  2465. }
  2466. }
  2467. /**
  2468. * Get the width of the select in pixels where the text area and icon has
  2469. * been included.
  2470. *
  2471. * @return The width in pixels
  2472. */
  2473. private int getMainWidth() {
  2474. return getOffsetWidth();
  2475. }
  2476. @Override
  2477. public void setWidth(String width) {
  2478. super.setWidth(width);
  2479. if (!width.isEmpty()) {
  2480. tb.setWidth("100%");
  2481. }
  2482. }
  2483. /**
  2484. * Handles special behavior of the mouse down event.
  2485. *
  2486. * @param event
  2487. */
  2488. private void handleMouseDownEvent(Event event) {
  2489. /*
  2490. * Prevent the keyboard focus from leaving the textfield by preventing
  2491. * the default behavior of the browser. Fixes #4285.
  2492. */
  2493. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  2494. debug("VComboBox: blocking mouseDown event to avoid blur");
  2495. event.preventDefault();
  2496. event.stopPropagation();
  2497. /*
  2498. * In IE the above wont work, the blur event will still trigger. So,
  2499. * we set a flag here to prevent the next blur event from happening.
  2500. * This is not needed if do not already have focus, in that case
  2501. * there will not be any blur event and we should not cancel the
  2502. * next blur.
  2503. */
  2504. if (BrowserInfo.get().isIE() && focused) {
  2505. preventNextBlurEventInIE = true;
  2506. debug("VComboBox: Going to prevent next blur event on IE");
  2507. }
  2508. }
  2509. }
  2510. @Override
  2511. public void onMouseDown(MouseDownEvent event) {
  2512. debug("VComboBox.onMouseDown(): blocking mouseDown event to avoid blur");
  2513. event.preventDefault();
  2514. event.stopPropagation();
  2515. /*
  2516. * In IE the above wont work, the blur event will still trigger. So, we
  2517. * set a flag here to prevent the next blur event from happening. This
  2518. * is not needed if do not already have focus, in that case there will
  2519. * not be any blur event and we should not cancel the next blur.
  2520. */
  2521. if (BrowserInfo.get().isIE() && focused) {
  2522. preventNextBlurEventInIE = true;
  2523. debug("VComboBox: Going to prevent next blur event on IE");
  2524. }
  2525. }
  2526. @Override
  2527. protected void onDetach() {
  2528. super.onDetach();
  2529. suggestionPopup.hide();
  2530. }
  2531. @Override
  2532. public com.google.gwt.user.client.Element getSubPartElement(
  2533. String subPart) {
  2534. String[] parts = subPart.split("/");
  2535. if ("textbox".equals(parts[0])) {
  2536. return tb.getElement();
  2537. } else if ("button".equals(parts[0])) {
  2538. return popupOpener.getElement();
  2539. } else if ("popup".equals(parts[0]) && suggestionPopup.isAttached()) {
  2540. if (parts.length == 2) {
  2541. return suggestionPopup.menu.getSubPartElement(parts[1]);
  2542. }
  2543. return suggestionPopup.getElement();
  2544. }
  2545. return null;
  2546. }
  2547. @Override
  2548. public String getSubPartName(
  2549. com.google.gwt.user.client.Element subElement) {
  2550. if (tb.getElement().isOrHasChild(subElement)) {
  2551. return "textbox";
  2552. } else if (popupOpener.getElement().isOrHasChild(subElement)) {
  2553. return "button";
  2554. } else if (suggestionPopup.getElement().isOrHasChild(subElement)) {
  2555. return "popup";
  2556. }
  2557. return null;
  2558. }
  2559. @Override
  2560. public void setAriaRequired(boolean required) {
  2561. AriaHelper.handleInputRequired(tb, required);
  2562. }
  2563. @Override
  2564. public void setAriaInvalid(boolean invalid) {
  2565. AriaHelper.handleInputInvalid(tb, invalid);
  2566. }
  2567. @Override
  2568. public void bindAriaCaption(
  2569. com.google.gwt.user.client.Element captionElement) {
  2570. AriaHelper.bindCaption(tb, captionElement);
  2571. }
  2572. @Override
  2573. public boolean isWorkPending() {
  2574. return dataReceivedHandler.isWaitingForFilteringResponse()
  2575. || suggestionPopup.lazyPageScroller.isRunning();
  2576. }
  2577. /**
  2578. * Sets the caption of selected item, if "scroll to page" is disabled. This
  2579. * method is meant for internal use and may change in future versions.
  2580. *
  2581. * @since 7.7
  2582. * @param selectedCaption
  2583. * the caption of selected item
  2584. */
  2585. public void setSelectedCaption(String selectedCaption) {
  2586. explicitSelectedCaption = selectedCaption;
  2587. if (selectedCaption != null) {
  2588. setText(selectedCaption);
  2589. }
  2590. }
  2591. /**
  2592. * This method is meant for internal use and may change in future versions.
  2593. *
  2594. * @since 7.7
  2595. * @return the caption of selected item, if "scroll to page" is disabled
  2596. */
  2597. public String getSelectedCaption() {
  2598. return explicitSelectedCaption;
  2599. }
  2600. /**
  2601. * Returns a handler receiving notifications from the connector about
  2602. * communications.
  2603. *
  2604. * @return the dataReceivedHandler
  2605. */
  2606. public DataReceivedHandler getDataReceivedHandler() {
  2607. return dataReceivedHandler;
  2608. }
  2609. /**
  2610. * Sets the number of items to show per page, or 0 for showing all items.
  2611. *
  2612. * @param pageLength
  2613. * new page length or 0 for all items
  2614. */
  2615. public void setPageLength(int pageLength) {
  2616. this.pageLength = pageLength;
  2617. }
  2618. /**
  2619. * Sets the suggestion pop-up's width as a CSS string. By using relative
  2620. * units (e.g. "50%") it's possible to set the popup's width relative to the
  2621. * ComboBox itself.
  2622. *
  2623. * @param suggestionPopupWidth
  2624. * new popup width as CSS string, null for old default width
  2625. * calculation based on items
  2626. */
  2627. public void setSuggestionPopupWidth(String suggestionPopupWidth) {
  2628. this.suggestionPopupWidth = suggestionPopupWidth;
  2629. }
  2630. /**
  2631. * Sets whether creation of new items when there is no match is allowed or
  2632. * not.
  2633. *
  2634. * @param allowNewItems
  2635. * true to allow creation of new items, false to only allow
  2636. * selection of existing items
  2637. */
  2638. public void setAllowNewItems(boolean allowNewItems) {
  2639. this.allowNewItems = allowNewItems;
  2640. }
  2641. /**
  2642. * Sets the total number of suggestions.
  2643. * <p>
  2644. * NOTE: this excluded the possible null selection item!
  2645. * <p>
  2646. * NOTE: this just updates the state, but doesn't update any UI.
  2647. *
  2648. * @since 8.0
  2649. * @param totalSuggestions
  2650. * total number of suggestions
  2651. */
  2652. public void setTotalSuggestions(int totalSuggestions) {
  2653. this.totalSuggestions = totalSuggestions;
  2654. }
  2655. /**
  2656. * Gets the total number of suggestions, excluding the null selection item.
  2657. *
  2658. * @since 8.0
  2659. * @return total number of suggestions
  2660. */
  2661. public int getTotalSuggestions() {
  2662. return totalSuggestions;
  2663. }
  2664. /**
  2665. * Gets the total number of suggestions, including the possible null
  2666. * selection item, if it should be visible.
  2667. *
  2668. * @return total number of suggestions with null selection items
  2669. */
  2670. private int getTotalSuggestionsIncludingNullSelectionItem() {
  2671. return getTotalSuggestions()
  2672. + (getNullSelectionItemShouldBeVisible() ? 1 : 0);
  2673. }
  2674. /**
  2675. * Returns null selection item should be visible or not.
  2676. * <p>
  2677. * NOTE: this checks for any entered filter value, and whether the feature
  2678. * is enabled
  2679. *
  2680. * @since 8.0
  2681. * @return {@code true} if it should be visible, {@code}
  2682. */
  2683. public boolean getNullSelectionItemShouldBeVisible() {
  2684. return nullSelectionAllowed && "".equals(lastFilter);
  2685. }
  2686. /**
  2687. * Gets the empty selection caption.
  2688. *
  2689. * @since 8.0.7
  2690. * @return the empty selection caption
  2691. */
  2692. public String getEmptySelectionCaption() {
  2693. return emptySelectionCaption;
  2694. }
  2695. /**
  2696. * Sets the empty selection caption for this VComboBox. The text is
  2697. * displayed in the text input when nothing is selected.
  2698. *
  2699. * @param emptySelectionCaption
  2700. * the empty selection caption
  2701. *
  2702. * @since 8.0.7
  2703. */
  2704. public void setEmptySelectionCaption(String emptySelectionCaption) {
  2705. this.emptySelectionCaption = emptySelectionCaption;
  2706. if (selectedOptionKey == null) {
  2707. setText(emptySelectionCaption);
  2708. }
  2709. }
  2710. private static Logger getLogger() {
  2711. return Logger.getLogger(VComboBox.class.getName());
  2712. }
  2713. }