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

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