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

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