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

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