Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

VComboBox.java 103KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Date;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Locale;
  23. import java.util.Set;
  24. import 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. getElement().setAttribute("autocomplete", "nope");
  1215. }
  1216. /**
  1217. * Overridden to avoid selecting text when text input is disabled.
  1218. */
  1219. @Override
  1220. public void setSelectionRange(int pos, int length) {
  1221. if (textInputEnabled) {
  1222. /*
  1223. * set selection range with a backwards direction: anchor at the
  1224. * back, focus at the front. This means that items that are too
  1225. * long to display will display from the start and not the end
  1226. * even on Firefox.
  1227. *
  1228. * We need the JSNI function to set selection range so that we
  1229. * can use the optional direction attribute to set the anchor to
  1230. * the end and the focus to the start. This makes Firefox work
  1231. * the same way as other browsers (#13477)
  1232. */
  1233. WidgetUtil.setSelectionRange(getElement(), pos, length,
  1234. "backward");
  1235. } else {
  1236. /*
  1237. * Setting the selectionrange for an uneditable textbox leads to
  1238. * unwanted behavior when the width of the textbox is narrower
  1239. * than the width of the entry: the end of the entry is shown
  1240. * instead of the beginning. (see #13477)
  1241. *
  1242. * To avoid this, we set the caret to the beginning of the line.
  1243. */
  1244. super.setSelectionRange(0, 0);
  1245. }
  1246. }
  1247. }
  1248. /**
  1249. * Handler receiving notifications from the connector and updating the
  1250. * widget state accordingly.
  1251. *
  1252. * This class is still subject to change and should not be considered as
  1253. * public stable API.
  1254. *
  1255. * @since 8.0
  1256. */
  1257. public class DataReceivedHandler {
  1258. private Runnable navigationCallback = null;
  1259. /**
  1260. * Set true when popupopened has been clicked. Cleared on each
  1261. * UIDL-update. This handles the special case where are not filtering
  1262. * yet and the selected value has changed on the server-side. See #2119
  1263. * <p>
  1264. * For internal use only. May be removed or replaced in the future.
  1265. */
  1266. private boolean popupOpenerClicked = false;
  1267. /** For internal use only. May be removed or replaced in the future. */
  1268. private boolean waitingForFilteringResponse = false;
  1269. private boolean initialData = true;
  1270. private String pendingUserInput = null;
  1271. private boolean showPopup = false;
  1272. /**
  1273. * Called by the connector when new data for the last requested filter
  1274. * is received from the server.
  1275. */
  1276. public void dataReceived() {
  1277. if (initialData) {
  1278. suggestionPopup.menu.setSuggestions(currentSuggestions);
  1279. performSelection(serverSelectedKey, true, true);
  1280. updateSuggestionPopupMinWidth();
  1281. updateRootWidth();
  1282. initialData = false;
  1283. return;
  1284. }
  1285. suggestionPopup.menu.setSuggestions(currentSuggestions);
  1286. if (!waitingForFilteringResponse && suggestionPopup.isAttached()) {
  1287. showPopup = true;
  1288. }
  1289. if (showPopup) {
  1290. suggestionPopup.showSuggestions(currentPage);
  1291. }
  1292. waitingForFilteringResponse = false;
  1293. if (pendingUserInput != null) {
  1294. boolean pendingHandled = suggestionPopup.menu.handledNewItem == pendingUserInput;
  1295. suggestionPopup.menu
  1296. .actOnEnteredValueAfterFiltering(pendingUserInput);
  1297. if (!allowNewItems || (pendingHandled
  1298. && suggestionPopup.menu.handledNewItem == null)) {
  1299. pendingUserInput = null;
  1300. } else {
  1301. waitingForFilteringResponse = true;
  1302. }
  1303. } else if (popupOpenerClicked) {
  1304. // make sure the current item is selected in the popup
  1305. suggestionPopup.menu.highlightSelectedItem();
  1306. } else {
  1307. navigateItemAfterPageChange();
  1308. }
  1309. if (!showPopup) {
  1310. suggestionPopup.hide();
  1311. }
  1312. popupOpenerClicked = false;
  1313. showPopup = false;
  1314. }
  1315. /**
  1316. * Perform filtering with the user entered string and when the results
  1317. * are received, perform any action appropriate for the user input
  1318. * (select an item or create a new one).
  1319. *
  1320. * @param value
  1321. * user input
  1322. */
  1323. public void reactOnInputWhenReady(String value) {
  1324. pendingUserInput = value;
  1325. showPopup = false;
  1326. filterOptions(0, value);
  1327. }
  1328. public boolean isPending(String value) {
  1329. return value != null && value.equals(pendingUserInput);
  1330. }
  1331. /*
  1332. * This method navigates to the proper item in the combobox page. This
  1333. * should be executed after setSuggestions() method which is called from
  1334. * VComboBox.showSuggestions(). ShowSuggestions() method builds the page
  1335. * content. As far as setSuggestions() method is called as deferred,
  1336. * navigateItemAfterPageChange method should be also be called as
  1337. * deferred. #11333
  1338. */
  1339. private void navigateItemAfterPageChange() {
  1340. if (navigationCallback != null) {
  1341. // navigationCallback is not reset here but after any server
  1342. // request in case you are in between two requests both changing
  1343. // the page back and forth
  1344. // we're paging w/ arrows
  1345. navigationCallback.run();
  1346. navigationCallback = null;
  1347. }
  1348. }
  1349. /**
  1350. * Called by the connector any pending navigation operations should be
  1351. * cleared.
  1352. */
  1353. public void clearPendingNavigation() {
  1354. navigationCallback = null;
  1355. }
  1356. /**
  1357. * Set a callback that is invoked when a page change occurs if there
  1358. * have not been intervening requests to the server. The callback is
  1359. * reset when any additional request is made to the server.
  1360. *
  1361. * @param callback
  1362. * method to call after filtering has completed
  1363. */
  1364. public void setNavigationCallback(Runnable callback) {
  1365. showPopup = true;
  1366. navigationCallback = callback;
  1367. }
  1368. /**
  1369. * Record that the popup opener has been clicked and the popup should be
  1370. * opened on the next request.
  1371. *
  1372. * This handles the special case where are not filtering yet and the
  1373. * selected value has changed on the server-side. See #2119. The flag is
  1374. * cleared on each server reply.
  1375. */
  1376. public void popupOpenerClicked() {
  1377. popupOpenerClicked = true;
  1378. showPopup = true;
  1379. }
  1380. /**
  1381. * Cancel a pending request to perform post-filtering actions.
  1382. */
  1383. private void cancelPendingPostFiltering() {
  1384. pendingUserInput = null;
  1385. waitingForFilteringResponse = false;
  1386. }
  1387. /**
  1388. * Called by the connector when it has finished handling any reply from
  1389. * the server, regardless of what was updated.
  1390. */
  1391. public void serverReplyHandled() {
  1392. popupOpenerClicked = false;
  1393. // if (!initDone) {
  1394. // debug("VComboBox: init done, updating widths");
  1395. // // Calculate minimum textarea width
  1396. // updateSuggestionPopupMinWidth();
  1397. // updateRootWidth();
  1398. // initDone = true;
  1399. // }
  1400. }
  1401. /**
  1402. * For internal use only - this method will be removed in the future.
  1403. *
  1404. * @return true if the combo box is waiting for a reply from the server
  1405. * with a new page of data, false otherwise
  1406. */
  1407. public boolean isWaitingForFilteringResponse() {
  1408. return waitingForFilteringResponse;
  1409. }
  1410. /**
  1411. * For internal use only - this method will be removed in the future.
  1412. *
  1413. * @return true if the combo box is waiting for initial data from the
  1414. * server, false otherwise
  1415. */
  1416. public boolean isWaitingForInitialData() {
  1417. return initialData;
  1418. }
  1419. /**
  1420. * Set a flag that filtering of options is pending a response from the
  1421. * server.
  1422. */
  1423. private void startWaitingForFilteringResponse() {
  1424. waitingForFilteringResponse = true;
  1425. }
  1426. /**
  1427. * Perform selection (if appropriate) based on a reply from the server.
  1428. * When this method is called, the suggestions have been reset if new
  1429. * ones (different from the previous list) were received from the
  1430. * server.
  1431. *
  1432. * @param selectedKey
  1433. * new selected key or null if none given by the server
  1434. * @param selectedCaption
  1435. * new selected item caption if sent by the server or null -
  1436. * this is used when the selected item is not on the current
  1437. * page
  1438. * @param selectedIconUri
  1439. * new selected item icon if sent by the server or {@ code
  1440. * null} to clear
  1441. */
  1442. public void updateSelectionFromServer(String selectedKey,
  1443. String selectedCaption, String selectedIconUri) {
  1444. boolean oldSuggestionTextMatchTheOldSelection = currentSuggestion != null
  1445. && currentSuggestion.getReplacementString()
  1446. .equals(tb.getText());
  1447. serverSelectedKey = selectedKey;
  1448. performSelection(selectedKey, oldSuggestionTextMatchTheOldSelection,
  1449. !isWaitingForFilteringResponse() || popupOpenerClicked);
  1450. cancelPendingPostFiltering();
  1451. setSelectedCaption(selectedCaption);
  1452. setSelectedItemIcon(selectedIconUri);
  1453. }
  1454. }
  1455. // TODO decide whether this should change - affects themes and v7
  1456. public static final String CLASSNAME = "v-filterselect";
  1457. private static final String STYLE_NO_INPUT = "no-input";
  1458. /** For internal use only. May be removed or replaced in the future. */
  1459. public int pageLength = 10;
  1460. private boolean enableDebug = false;
  1461. private final FlowPanel panel = new FlowPanel();
  1462. /**
  1463. * The text box where the filter is written
  1464. * <p>
  1465. * For internal use only. May be removed or replaced in the future.
  1466. */
  1467. public final TextBox tb;
  1468. /** For internal use only. May be removed or replaced in the future. */
  1469. public final SuggestionPopup suggestionPopup;
  1470. /**
  1471. * Used when measuring the width of the popup
  1472. */
  1473. private final HTML popupOpener = new HTML("");
  1474. private class IconWidget extends Widget {
  1475. IconWidget(Icon icon) {
  1476. setElement(icon.getElement());
  1477. }
  1478. }
  1479. private IconWidget selectedItemIcon;
  1480. /** For internal use only. May be removed or replaced in the future. */
  1481. public ComboBoxConnector connector;
  1482. /** For internal use only. May be removed or replaced in the future. */
  1483. public int currentPage;
  1484. /**
  1485. * A collection of available suggestions (options) as received from the
  1486. * server.
  1487. * <p>
  1488. * For internal use only. May be removed or replaced in the future.
  1489. */
  1490. public final List<ComboBoxSuggestion> currentSuggestions = new ArrayList<>();
  1491. /** For internal use only. May be removed or replaced in the future. */
  1492. public String serverSelectedKey;
  1493. /** For internal use only. May be removed or replaced in the future. */
  1494. public String selectedOptionKey;
  1495. /** For internal use only. May be removed or replaced in the future. */
  1496. public boolean initDone = false;
  1497. /** For internal use only. May be removed or replaced in the future. */
  1498. public String lastFilter = "";
  1499. /**
  1500. * The current suggestion selected from the dropdown. This is one of the
  1501. * values in currentSuggestions except when filtering, in this case
  1502. * currentSuggestion might not be in currentSuggestions.
  1503. * <p>
  1504. * For internal use only. May be removed or replaced in the future.
  1505. */
  1506. public ComboBoxSuggestion currentSuggestion;
  1507. /** For internal use only. May be removed or replaced in the future. */
  1508. public boolean allowNewItems;
  1509. /** Total number of suggestions, excluding null selection item. */
  1510. private int totalSuggestions;
  1511. /** For internal use only. May be removed or replaced in the future. */
  1512. public boolean nullSelectionAllowed;
  1513. /** For internal use only. May be removed or replaced in the future. */
  1514. public boolean nullSelectItem;
  1515. /** For internal use only. May be removed or replaced in the future. */
  1516. public boolean enabled;
  1517. /** For internal use only. May be removed or replaced in the future. */
  1518. public boolean readonly;
  1519. /** For internal use only. May be removed or replaced in the future. */
  1520. public String inputPrompt = "";
  1521. /** For internal use only. May be removed or replaced in the future. */
  1522. public int suggestionPopupMinWidth = 0;
  1523. public String suggestionPopupWidth = null;
  1524. private int popupWidth = -1;
  1525. /**
  1526. * Stores the last new item string to avoid double submissions. Cleared on
  1527. * uidl updates.
  1528. * <p>
  1529. * For internal use only. May be removed or replaced in the future.
  1530. */
  1531. public String lastNewItemString;
  1532. /** For internal use only. May be removed or replaced in the future. */
  1533. public boolean focused = false;
  1534. /**
  1535. * If set to false, the component should not allow entering text to the
  1536. * field even for filtering.
  1537. */
  1538. private boolean textInputEnabled = true;
  1539. private String emptySelectionCaption = "";
  1540. private final DataReceivedHandler dataReceivedHandler = new DataReceivedHandler();
  1541. /**
  1542. * Default constructor.
  1543. */
  1544. public VComboBox() {
  1545. tb = createTextBox();
  1546. suggestionPopup = createSuggestionPopup();
  1547. popupOpener.addMouseDownHandler(VComboBox.this);
  1548. Roles.getButtonRole().setAriaHiddenState(popupOpener.getElement(),
  1549. true);
  1550. Roles.getButtonRole().set(popupOpener.getElement());
  1551. panel.add(tb);
  1552. panel.add(popupOpener);
  1553. initWidget(panel);
  1554. Roles.getComboboxRole().set(panel.getElement());
  1555. tb.addKeyDownHandler(this);
  1556. tb.addKeyUpHandler(this);
  1557. tb.addFocusHandler(this);
  1558. tb.addBlurHandler(this);
  1559. panel.addDomHandler(this, ClickEvent.getType());
  1560. setStyleName(CLASSNAME);
  1561. sinkEvents(Event.ONPASTE);
  1562. }
  1563. private static double getMarginBorderPaddingWidth(Element element) {
  1564. final ComputedStyle s = new ComputedStyle(element);
  1565. return s.getMarginWidth() + s.getBorderWidth() + s.getPaddingWidth();
  1566. }
  1567. /*
  1568. * (non-Javadoc)
  1569. *
  1570. * @see
  1571. * com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt
  1572. * .user.client.Event)
  1573. */
  1574. @Override
  1575. public void onBrowserEvent(Event event) {
  1576. super.onBrowserEvent(event);
  1577. if (event.getTypeInt() == Event.ONPASTE) {
  1578. if (textInputEnabled && connector.isEnabled()) {
  1579. filterOptions(currentPage);
  1580. }
  1581. }
  1582. }
  1583. /**
  1584. * This method will create the TextBox used by the VComboBox instance. It is
  1585. * invoked during the Constructor and should only be overridden if a custom
  1586. * TextBox shall be used. The overriding method cannot use any instance
  1587. * variables.
  1588. *
  1589. * @since 7.1.5
  1590. * @return TextBox instance used by this VComboBox
  1591. */
  1592. protected TextBox createTextBox() {
  1593. return new FilterSelectTextBox();
  1594. }
  1595. /**
  1596. * This method will create the SuggestionPopup used by the VComboBox
  1597. * instance. It is invoked during the Constructor and should only be
  1598. * overridden if a custom SuggestionPopup shall be used. The overriding
  1599. * method cannot use any instance variables.
  1600. *
  1601. * @since 7.1.5
  1602. * @return SuggestionPopup instance used by this VComboBox
  1603. */
  1604. protected SuggestionPopup createSuggestionPopup() {
  1605. return new SuggestionPopup();
  1606. }
  1607. @Override
  1608. public void setStyleName(String style) {
  1609. super.setStyleName(style);
  1610. updateStyleNames();
  1611. }
  1612. @Override
  1613. public void setStylePrimaryName(String style) {
  1614. super.setStylePrimaryName(style);
  1615. updateStyleNames();
  1616. }
  1617. protected void updateStyleNames() {
  1618. tb.setStyleName(getStylePrimaryName() + "-input");
  1619. popupOpener.setStyleName(getStylePrimaryName() + "-button");
  1620. suggestionPopup.setStyleName(getStylePrimaryName() + "-suggestpopup");
  1621. }
  1622. /**
  1623. * Does the Select have more pages?
  1624. *
  1625. * @return true if a next page exists, else false if the current page is the
  1626. * last page
  1627. */
  1628. public boolean hasNextPage() {
  1629. return pageLength > 0
  1630. && getTotalSuggestionsIncludingNullSelectionItem() > (currentPage
  1631. + 1) * pageLength;
  1632. }
  1633. /**
  1634. * Filters the options at a certain page. Uses the text box input as a
  1635. * filter and ensures the popup is opened when filtering results are
  1636. * available.
  1637. *
  1638. * @param page
  1639. * The page which items are to be filtered
  1640. */
  1641. public void filterOptions(int page) {
  1642. dataReceivedHandler.popupOpenerClicked();
  1643. filterOptions(page, tb.getText());
  1644. }
  1645. /**
  1646. * Filters the options at certain page using the given filter.
  1647. *
  1648. * @param page
  1649. * The page to filter
  1650. * @param filter
  1651. * The filter to apply to the components
  1652. */
  1653. public void filterOptions(int page, String filter) {
  1654. debug("VComboBox: filterOptions(" + page + ", " + filter + ")");
  1655. if (filter.equals(lastFilter) && currentPage == page
  1656. && suggestionPopup.isAttached()) {
  1657. // already have the page
  1658. dataReceivedHandler.dataReceived();
  1659. return;
  1660. }
  1661. if (!filter.equals(lastFilter)) {
  1662. // when filtering, let the server decide the page unless we've
  1663. // set the filter to empty and explicitly said that we want to see
  1664. // the results starting from page 0.
  1665. if (filter.isEmpty() && page != 0) {
  1666. // let server decide
  1667. page = -1;
  1668. } else {
  1669. page = 0;
  1670. }
  1671. }
  1672. dataReceivedHandler.startWaitingForFilteringResponse();
  1673. connector.requestPage(page, filter);
  1674. lastFilter = filter;
  1675. // If the data was updated from cache, the page has been updated too, if
  1676. // not, update
  1677. if (dataReceivedHandler.isWaitingForFilteringResponse()) {
  1678. currentPage = page;
  1679. }
  1680. }
  1681. /** For internal use only. May be removed or replaced in the future. */
  1682. public void updateReadOnly() {
  1683. debug("VComboBox: updateReadOnly()");
  1684. tb.setReadOnly(readonly || !textInputEnabled);
  1685. }
  1686. public void setTextInputAllowed(boolean textInputAllowed) {
  1687. debug("VComboBox: setTextInputAllowed()");
  1688. // Always update styles as they might have been overwritten
  1689. if (textInputAllowed) {
  1690. removeStyleDependentName(STYLE_NO_INPUT);
  1691. Roles.getTextboxRole().removeAriaReadonlyProperty(tb.getElement());
  1692. } else {
  1693. addStyleDependentName(STYLE_NO_INPUT);
  1694. Roles.getTextboxRole().setAriaReadonlyProperty(tb.getElement(),
  1695. true);
  1696. }
  1697. if (textInputEnabled != textInputAllowed) {
  1698. textInputEnabled = textInputAllowed;
  1699. updateReadOnly();
  1700. }
  1701. }
  1702. /**
  1703. * Sets the text in the text box.
  1704. *
  1705. * @param text
  1706. * the text to set in the text box
  1707. */
  1708. public void setText(final String text) {
  1709. /**
  1710. * To leave caret in the beginning of the line. SetSelectionRange
  1711. * wouldn't work on IE (see #13477)
  1712. */
  1713. Direction previousDirection = tb.getDirection();
  1714. tb.setDirection(Direction.RTL);
  1715. tb.setText(text);
  1716. tb.setDirection(previousDirection);
  1717. }
  1718. /**
  1719. * Set or reset the placeholder attribute for the text field.
  1720. *
  1721. * @param placeholder
  1722. * new placeholder string or null for none
  1723. */
  1724. public void setPlaceholder(String placeholder) {
  1725. inputPrompt = placeholder;
  1726. updatePlaceholder();
  1727. }
  1728. /**
  1729. * Update placeholder visibility (hidden when read-only or disabled).
  1730. */
  1731. public void updatePlaceholder() {
  1732. if (inputPrompt != null && enabled && !readonly) {
  1733. tb.getElement().setAttribute("placeholder", inputPrompt);
  1734. } else {
  1735. tb.getElement().removeAttribute("placeholder");
  1736. }
  1737. }
  1738. /**
  1739. * Triggered when a suggestion is selected.
  1740. *
  1741. * @param suggestion
  1742. * The suggestion that just got selected.
  1743. */
  1744. public void onSuggestionSelected(ComboBoxSuggestion suggestion) {
  1745. if (enableDebug) {
  1746. debug("VComboBox: onSuggestionSelected(" + suggestion.caption + ": "
  1747. + suggestion.key + ")");
  1748. }
  1749. // special handling of null selection
  1750. if (suggestion.key.isEmpty()) {
  1751. onNullSelected();
  1752. return;
  1753. }
  1754. dataReceivedHandler.cancelPendingPostFiltering();
  1755. currentSuggestion = suggestion;
  1756. String newKey = suggestion.getOptionKey();
  1757. String text = suggestion.getReplacementString();
  1758. setText(text);
  1759. setSelectedItemIcon(suggestion.getIconUri());
  1760. if (!newKey.equals(selectedOptionKey)) {
  1761. selectedOptionKey = newKey;
  1762. connector.sendSelection(selectedOptionKey);
  1763. setSelectedCaption(text);
  1764. // currentPage = -1; // forget the page
  1765. }
  1766. suggestionPopup.hide();
  1767. }
  1768. /**
  1769. * Triggered when an empty value is selected and null selection is allowed.
  1770. */
  1771. public void onNullSelected() {
  1772. if (enableDebug) {
  1773. debug("VComboBox: onNullSelected()");
  1774. }
  1775. dataReceivedHandler.cancelPendingPostFiltering();
  1776. currentSuggestion = null;
  1777. setText(getEmptySelectionCaption());
  1778. setSelectedItemIcon(null);
  1779. if (!"".equals(selectedOptionKey) || selectedOptionKey != null) {
  1780. selectedOptionKey = "";
  1781. setSelectedCaption("");
  1782. connector.sendSelection(null);
  1783. // currentPage = 0;
  1784. }
  1785. updatePlaceholder();
  1786. suggestionPopup.hide();
  1787. }
  1788. /**
  1789. * Sets the icon URI of the selected item. The icon is shown on the left
  1790. * side of the item caption text. Set the URI to null to remove the icon.
  1791. *
  1792. * @param iconUri
  1793. * The URI of the icon, or null to remove icon
  1794. */
  1795. public void setSelectedItemIcon(String iconUri) {
  1796. if (selectedItemIcon != null) {
  1797. panel.remove(selectedItemIcon);
  1798. }
  1799. if (iconUri == null || iconUri.isEmpty()) {
  1800. if (selectedItemIcon != null) {
  1801. selectedItemIcon = null;
  1802. afterSelectedItemIconChange();
  1803. }
  1804. } else {
  1805. selectedItemIcon = new IconWidget(
  1806. connector.getConnection().getIcon(iconUri));
  1807. selectedItemIcon.addDomHandler(VComboBox.this,
  1808. ClickEvent.getType());
  1809. selectedItemIcon.addDomHandler(VComboBox.this,
  1810. MouseDownEvent.getType());
  1811. selectedItemIcon.addDomHandler(
  1812. event -> afterSelectedItemIconChange(),
  1813. LoadEvent.getType());
  1814. panel.insert(selectedItemIcon, 0);
  1815. afterSelectedItemIconChange();
  1816. }
  1817. }
  1818. private void afterSelectedItemIconChange() {
  1819. if (BrowserInfo.get().isWebkit()) {
  1820. // Some browsers need a nudge to reposition the text field
  1821. forceReflow();
  1822. }
  1823. updateRootWidth();
  1824. if (selectedItemIcon != null) {
  1825. updateSelectedIconPosition();
  1826. }
  1827. }
  1828. /**
  1829. * Perform selection based on a message from the server.
  1830. *
  1831. * The special case where the selected item is not on the current page is
  1832. * handled separately by the caller.
  1833. *
  1834. * @param selectedKey
  1835. * non-empty selected item key
  1836. * @param forceUpdateText
  1837. * true to force the text box value to match the suggestion text
  1838. * @param updatePromptAndSelectionIfMatchFound
  1839. */
  1840. private void performSelection(String selectedKey, boolean forceUpdateText,
  1841. boolean updatePromptAndSelectionIfMatchFound) {
  1842. if (selectedKey == null || selectedKey.isEmpty()) {
  1843. currentSuggestion = null; // #13217
  1844. selectedOptionKey = null;
  1845. setText(getEmptySelectionCaption());
  1846. }
  1847. // some item selected
  1848. for (ComboBoxSuggestion suggestion : currentSuggestions) {
  1849. String suggestionKey = suggestion.getOptionKey();
  1850. if (!suggestionKey.equals(selectedKey)) {
  1851. continue;
  1852. }
  1853. // at this point, suggestion key matches the new selection key
  1854. if (updatePromptAndSelectionIfMatchFound) {
  1855. if (!suggestionKey.equals(selectedOptionKey) || suggestion
  1856. .getReplacementString().equals(tb.getText())
  1857. || forceUpdateText) {
  1858. // Update text field if we've got a new
  1859. // selection
  1860. // Also update if we've got the same text to
  1861. // retain old text selection behavior
  1862. // OR if selected item caption is changed.
  1863. setText(suggestion.getReplacementString());
  1864. selectedOptionKey = suggestionKey;
  1865. }
  1866. }
  1867. currentSuggestion = suggestion;
  1868. // only a single item can be selected
  1869. break;
  1870. }
  1871. }
  1872. private void forceReflow() {
  1873. WidgetUtil.setStyleTemporarily(tb.getElement(), "zoom", "1");
  1874. }
  1875. /**
  1876. * Positions the icon vertically in the middle. Should be called after the
  1877. * icon has loaded
  1878. */
  1879. private void updateSelectedIconPosition() {
  1880. // Position icon vertically to middle
  1881. int availableHeight = 0;
  1882. availableHeight = getOffsetHeight();
  1883. int iconHeight = WidgetUtil.getRequiredHeight(selectedItemIcon);
  1884. int marginTop = (availableHeight - iconHeight) / 2;
  1885. selectedItemIcon.getElement().getStyle().setMarginTop(marginTop,
  1886. Unit.PX);
  1887. }
  1888. private static Set<Integer> navigationKeyCodes = new HashSet<>();
  1889. static {
  1890. navigationKeyCodes.add(KeyCodes.KEY_DOWN);
  1891. navigationKeyCodes.add(KeyCodes.KEY_UP);
  1892. navigationKeyCodes.add(KeyCodes.KEY_PAGEDOWN);
  1893. navigationKeyCodes.add(KeyCodes.KEY_PAGEUP);
  1894. navigationKeyCodes.add(KeyCodes.KEY_ENTER);
  1895. }
  1896. /*
  1897. * (non-Javadoc)
  1898. *
  1899. * @see
  1900. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1901. * .event.dom.client.KeyDownEvent)
  1902. */
  1903. @Override
  1904. public void onKeyDown(KeyDownEvent event) {
  1905. if (enabled && !readonly) {
  1906. int keyCode = event.getNativeKeyCode();
  1907. if (enableDebug) {
  1908. debug("VComboBox: key down: " + keyCode);
  1909. }
  1910. if (dataReceivedHandler.isWaitingForFilteringResponse()
  1911. && navigationKeyCodes.contains(keyCode)
  1912. && (!allowNewItems || keyCode != KeyCodes.KEY_ENTER)) {
  1913. /*
  1914. * Keyboard navigation events should not be handled while we are
  1915. * waiting for a response. This avoids flickering, disappearing
  1916. * items, wrongly interpreted responses and more.
  1917. */
  1918. if (enableDebug) {
  1919. debug("Ignoring " + keyCode
  1920. + " because we are waiting for a filtering response");
  1921. }
  1922. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1923. event.stopPropagation();
  1924. return;
  1925. }
  1926. if (suggestionPopup.isAttached()) {
  1927. if (enableDebug) {
  1928. debug("Keycode " + keyCode + " target is popup");
  1929. }
  1930. popupKeyDown(event);
  1931. } else {
  1932. if (enableDebug) {
  1933. debug("Keycode " + keyCode + " target is text field");
  1934. }
  1935. inputFieldKeyDown(event);
  1936. }
  1937. }
  1938. }
  1939. private void debug(String string) {
  1940. if (enableDebug) {
  1941. getLogger().severe(string);
  1942. }
  1943. }
  1944. /**
  1945. * Triggered when a key is pressed in the text box
  1946. *
  1947. * @param event
  1948. * The KeyDownEvent
  1949. */
  1950. private void inputFieldKeyDown(KeyDownEvent event) {
  1951. if (enableDebug) {
  1952. debug("VComboBox: inputFieldKeyDown(" + event.getNativeKeyCode()
  1953. + ")");
  1954. }
  1955. switch (event.getNativeKeyCode()) {
  1956. case KeyCodes.KEY_DOWN:
  1957. case KeyCodes.KEY_UP:
  1958. case KeyCodes.KEY_PAGEDOWN:
  1959. case KeyCodes.KEY_PAGEUP:
  1960. // open popup as from gadget
  1961. filterOptions(-1, "");
  1962. tb.selectAll();
  1963. dataReceivedHandler.popupOpenerClicked();
  1964. break;
  1965. case KeyCodes.KEY_ENTER:
  1966. /*
  1967. * This only handles the case when new items is allowed, a text is
  1968. * entered, the popup opener button is clicked to close the popup
  1969. * and enter is then pressed (see #7560).
  1970. */
  1971. if (!allowNewItems) {
  1972. return;
  1973. }
  1974. if (currentSuggestion != null && tb.getText()
  1975. .equals(currentSuggestion.getReplacementString())) {
  1976. // Retain behavior from #6686 by returning without stopping
  1977. // propagation if there's nothing to do
  1978. return;
  1979. }
  1980. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  1981. suggestionPopup.hide();
  1982. event.stopPropagation();
  1983. break;
  1984. }
  1985. }
  1986. /**
  1987. * Triggered when a key was pressed in the suggestion popup.
  1988. *
  1989. * @param event
  1990. * The KeyDownEvent of the key
  1991. */
  1992. private void popupKeyDown(KeyDownEvent event) {
  1993. if (enableDebug) {
  1994. debug("VComboBox: popupKeyDown(" + event.getNativeKeyCode() + ")");
  1995. }
  1996. // Propagation of handled events is stopped so other handlers such as
  1997. // shortcut key handlers do not also handle the same events.
  1998. switch (event.getNativeKeyCode()) {
  1999. case KeyCodes.KEY_DOWN:
  2000. suggestionPopup.selectNextItem();
  2001. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2002. event.stopPropagation();
  2003. break;
  2004. case KeyCodes.KEY_UP:
  2005. suggestionPopup.selectPrevItem();
  2006. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2007. event.stopPropagation();
  2008. break;
  2009. case KeyCodes.KEY_PAGEDOWN:
  2010. selectNextPage();
  2011. event.stopPropagation();
  2012. break;
  2013. case KeyCodes.KEY_PAGEUP:
  2014. selectPrevPage();
  2015. event.stopPropagation();
  2016. break;
  2017. case KeyCodes.KEY_ESCAPE:
  2018. reset();
  2019. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2020. event.stopPropagation();
  2021. break;
  2022. case KeyCodes.KEY_TAB:
  2023. case KeyCodes.KEY_ENTER:
  2024. // queue this, may be cancelled by selection
  2025. int selectedIndex = suggestionPopup.menu.getSelectedIndex();
  2026. if (!allowNewItems && selectedIndex != -1) {
  2027. onSuggestionSelected(currentSuggestions.get(selectedIndex));
  2028. } else {
  2029. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  2030. }
  2031. suggestionPopup.hide();
  2032. event.stopPropagation();
  2033. break;
  2034. }
  2035. }
  2036. /*
  2037. * Show the prev page.
  2038. */
  2039. private void selectPrevPage() {
  2040. if (currentPage > 0) {
  2041. dataReceivedHandler.setNavigationCallback(
  2042. () -> suggestionPopup.selectLastItem());
  2043. filterOptions(currentPage - 1, lastFilter);
  2044. }
  2045. }
  2046. /*
  2047. * Show the next page.
  2048. */
  2049. private void selectNextPage() {
  2050. if (hasNextPage()) {
  2051. dataReceivedHandler.setNavigationCallback(
  2052. () -> suggestionPopup.selectFirstItem());
  2053. filterOptions(currentPage + 1, lastFilter);
  2054. }
  2055. }
  2056. /**
  2057. * Triggered when a key was depressed.
  2058. *
  2059. * @param event
  2060. * The KeyUpEvent of the key depressed
  2061. */
  2062. @Override
  2063. public void onKeyUp(KeyUpEvent event) {
  2064. if (enableDebug) {
  2065. debug("VComboBox: onKeyUp(" + event.getNativeKeyCode() + ")");
  2066. }
  2067. if (enabled && !readonly) {
  2068. switch (event.getNativeKeyCode()) {
  2069. case KeyCodes.KEY_ENTER:
  2070. case KeyCodes.KEY_TAB:
  2071. case KeyCodes.KEY_SHIFT:
  2072. case KeyCodes.KEY_CTRL:
  2073. case KeyCodes.KEY_ALT:
  2074. case KeyCodes.KEY_DOWN:
  2075. case KeyCodes.KEY_UP:
  2076. case KeyCodes.KEY_PAGEDOWN:
  2077. case KeyCodes.KEY_PAGEUP:
  2078. case KeyCodes.KEY_ESCAPE:
  2079. // NOP
  2080. break;
  2081. default:
  2082. if (textInputEnabled) {
  2083. // when filtering, we always want to see the results on the
  2084. // first page first.
  2085. filterOptions(0);
  2086. }
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. /**
  2092. * Resets the ComboBox to its initial state.
  2093. */
  2094. private void reset() {
  2095. debug("VComboBox: reset()");
  2096. // just fetch selected information from state
  2097. String text = connector.getState().selectedItemCaption;
  2098. setText(text == null ? getEmptySelectionCaption() : text);
  2099. setSelectedItemIcon(connector.getState().selectedItemIcon);
  2100. selectedOptionKey = (connector.getState().selectedItemKey);
  2101. if (selectedOptionKey == null || selectedOptionKey.isEmpty()) {
  2102. currentSuggestion = null; // #13217
  2103. selectedOptionKey = null;
  2104. updatePlaceholder();
  2105. } else {
  2106. currentSuggestion = currentSuggestions.stream()
  2107. .filter(suggestion -> suggestion.getOptionKey()
  2108. .equals(selectedOptionKey))
  2109. .findAny().orElse(null);
  2110. }
  2111. suggestionPopup.hide();
  2112. }
  2113. /**
  2114. * Listener for popupopener.
  2115. */
  2116. @Override
  2117. public void onClick(ClickEvent event) {
  2118. debug("VComboBox: onClick()");
  2119. if (textInputEnabled && event.getNativeEvent().getEventTarget()
  2120. .cast() == tb.getElement()) {
  2121. // Don't process clicks on the text field if text input is enabled
  2122. return;
  2123. }
  2124. if (enabled && !readonly) {
  2125. // ask suggestionPopup if it was just closed, we are using GWT
  2126. // Popup's auto close feature
  2127. if (!suggestionPopup.isJustClosed()) {
  2128. filterOptions(-1, "");
  2129. dataReceivedHandler.popupOpenerClicked();
  2130. }
  2131. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2132. focus();
  2133. tb.selectAll();
  2134. }
  2135. }
  2136. /**
  2137. * Update minimum width for combo box textarea based on input prompt and
  2138. * suggestions.
  2139. * <p>
  2140. * For internal use only. May be removed or replaced in the future.
  2141. */
  2142. public void updateSuggestionPopupMinWidth() {
  2143. debug("VComboBox: updateSuggestionPopupMinWidth()");
  2144. // used only to calculate minimum width
  2145. String captions = WidgetUtil.escapeHTML(inputPrompt);
  2146. for (ComboBoxSuggestion suggestion : currentSuggestions) {
  2147. // Collect captions so we can calculate minimum width for
  2148. // textarea
  2149. if (!captions.isEmpty()) {
  2150. captions += "|";
  2151. }
  2152. captions += WidgetUtil
  2153. .escapeHTML(suggestion.getReplacementString());
  2154. }
  2155. // Calculate minimum textarea width
  2156. suggestionPopupMinWidth = minWidth(captions);
  2157. }
  2158. /**
  2159. * Calculate minimum width for FilterSelect textarea.
  2160. * <p>
  2161. * For internal use only. May be removed or replaced in the future.
  2162. *
  2163. * @param captions
  2164. * pipe separated string listing all the captions to measure
  2165. * @return minimum width in pixels
  2166. */
  2167. public native int minWidth(String captions)
  2168. /*-{
  2169. if (!captions || captions.length <= 0)
  2170. return 0;
  2171. captions = captions.split("|");
  2172. var d = $wnd.document.createElement("div");
  2173. var html = "";
  2174. for (var i=0; i < captions.length; i++) {
  2175. html += "<div>" + captions[i] + "</div>";
  2176. // TODO apply same CSS classname as in suggestionmenu
  2177. }
  2178. d.style.position = "absolute";
  2179. d.style.top = "0";
  2180. d.style.left = "0";
  2181. d.style.visibility = "hidden";
  2182. d.innerHTML = html;
  2183. $wnd.document.body.appendChild(d);
  2184. var w = d.offsetWidth;
  2185. $wnd.document.body.removeChild(d);
  2186. return w;
  2187. }-*/;
  2188. /**
  2189. * A flag which prevents a focus event from taking place.
  2190. */
  2191. boolean iePreventNextFocus = false;
  2192. /*
  2193. * (non-Javadoc)
  2194. *
  2195. * @see
  2196. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  2197. * .dom.client.FocusEvent)
  2198. */
  2199. @Override
  2200. public void onFocus(FocusEvent event) {
  2201. debug("VComboBox: onFocus()");
  2202. /*
  2203. * When we disable a blur event in ie we need to refocus the textfield.
  2204. * This will cause a focus event we do not want to process, so in that
  2205. * case we just ignore it.
  2206. */
  2207. if (BrowserInfo.get().isIE() && iePreventNextFocus) {
  2208. iePreventNextFocus = false;
  2209. return;
  2210. }
  2211. focused = true;
  2212. updatePlaceholder();
  2213. addStyleDependentName("focus");
  2214. connector.sendFocusEvent();
  2215. connector.getConnection().getVTooltip()
  2216. .showAssistive(connector.getTooltipInfo(getElement()));
  2217. }
  2218. /**
  2219. * A flag which cancels the blur event and sets the focus back to the
  2220. * textfield if the Browser is IE.
  2221. */
  2222. boolean preventNextBlurEventInIE = false;
  2223. private String explicitSelectedCaption;
  2224. /*
  2225. * (non-Javadoc)
  2226. *
  2227. * @see
  2228. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  2229. * .dom.client.BlurEvent)
  2230. */
  2231. @Override
  2232. public void onBlur(BlurEvent event) {
  2233. debug("VComboBox: onBlur()");
  2234. if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) {
  2235. /*
  2236. * Clicking in the suggestion popup or on the popup button in IE
  2237. * causes a blur event to be sent for the field. In other browsers
  2238. * this is prevented by canceling/preventing default behavior for
  2239. * the focus event, in IE we handle it here by refocusing the text
  2240. * field and ignoring the resulting focus event for the textfield
  2241. * (in onFocus).
  2242. */
  2243. preventNextBlurEventInIE = false;
  2244. Element focusedElement = WidgetUtil.getFocusedElement();
  2245. if (getElement().isOrHasChild(focusedElement) || suggestionPopup
  2246. .getElement().isOrHasChild(focusedElement)) {
  2247. // IF the suggestion popup or another part of the VComboBox
  2248. // was focused, move the focus back to the textfield and prevent
  2249. // the triggered focus event (in onFocus).
  2250. iePreventNextFocus = true;
  2251. tb.setFocus(true);
  2252. return;
  2253. }
  2254. }
  2255. focused = false;
  2256. updatePlaceholder();
  2257. removeStyleDependentName("focus");
  2258. // Send new items when clicking out with the mouse.
  2259. if (!readonly) {
  2260. if (textInputEnabled && allowNewItems
  2261. && (currentSuggestion == null || !tb.getText().equals(
  2262. currentSuggestion.getReplacementString()))) {
  2263. dataReceivedHandler.reactOnInputWhenReady(tb.getText());
  2264. } else {
  2265. reset();
  2266. }
  2267. suggestionPopup.hide();
  2268. }
  2269. connector.sendBlurEvent();
  2270. }
  2271. /*
  2272. * (non-Javadoc)
  2273. *
  2274. * @see com.vaadin.client.Focusable#focus()
  2275. */
  2276. @Override
  2277. public void focus() {
  2278. debug("VComboBox: focus()");
  2279. focused = true;
  2280. updatePlaceholder();
  2281. tb.setFocus(true);
  2282. }
  2283. /**
  2284. * Calculates the width of the select if the select has undefined width.
  2285. * Should be called when the width changes or when the icon changes.
  2286. * <p>
  2287. * For internal use only. May be removed or replaced in the future.
  2288. */
  2289. public void updateRootWidth() {
  2290. debug("VComboBox: updateRootWidth()");
  2291. if (connector.isUndefinedWidth()) {
  2292. /*
  2293. * When the select has a undefined with we need to check that we are
  2294. * only setting the text box width relative to the first page width
  2295. * of the items. If this is not done the text box width will change
  2296. * when the popup is used to view longer items than the text box is
  2297. * wide.
  2298. */
  2299. int w = WidgetUtil.getRequiredWidth(this);
  2300. if (dataReceivedHandler.isWaitingForInitialData()
  2301. && suggestionPopupMinWidth > w) {
  2302. /*
  2303. * We want to compensate for the paddings just to preserve the
  2304. * exact size as in Vaadin 6.x, but we get here before
  2305. * MeasuredSize has been initialized.
  2306. * Util.measureHorizontalPaddingAndBorder does not work with
  2307. * border-box, so we must do this the hard way.
  2308. */
  2309. Style style = getElement().getStyle();
  2310. String originalPadding = style.getPadding();
  2311. String originalBorder = style.getBorderWidth();
  2312. style.setPaddingLeft(0, Unit.PX);
  2313. style.setBorderWidth(0, Unit.PX);
  2314. style.setProperty("padding", originalPadding);
  2315. style.setProperty("borderWidth", originalBorder);
  2316. // Use util.getRequiredWidth instead of getOffsetWidth here
  2317. int iconWidth = selectedItemIcon == null ? 0
  2318. : WidgetUtil.getRequiredWidth(selectedItemIcon);
  2319. int buttonWidth = popupOpener == null ? 0
  2320. : WidgetUtil.getRequiredWidth(popupOpener);
  2321. /*
  2322. * Instead of setting the width of the wrapper, set the width of
  2323. * the combobox. Subtract the width of the icon and the
  2324. * popupopener
  2325. */
  2326. tb.setWidth(suggestionPopupMinWidth - iconWidth - buttonWidth
  2327. + "px");
  2328. }
  2329. /*
  2330. * Lock the textbox width to its current value if it's not already
  2331. * locked. This can happen after setWidth("") which resets the
  2332. * textbox width to "100%".
  2333. */
  2334. if (!tb.getElement().getStyle().getWidth().endsWith("px")) {
  2335. int iconWidth = selectedItemIcon == null ? 0
  2336. : selectedItemIcon.getOffsetWidth();
  2337. tb.setWidth(tb.getOffsetWidth() - iconWidth + "px");
  2338. }
  2339. }
  2340. }
  2341. /**
  2342. * Get the width of the select in pixels where the text area and icon has
  2343. * been included.
  2344. *
  2345. * @return The width in pixels
  2346. */
  2347. private int getMainWidth() {
  2348. return getOffsetWidth();
  2349. }
  2350. @Override
  2351. public void setWidth(String width) {
  2352. super.setWidth(width);
  2353. if (!width.isEmpty()) {
  2354. tb.setWidth("100%");
  2355. }
  2356. }
  2357. /**
  2358. * Handles special behavior of the mouse down event.
  2359. *
  2360. * @param event
  2361. */
  2362. private void handleMouseDownEvent(Event event) {
  2363. /*
  2364. * Prevent the keyboard focus from leaving the textfield by preventing
  2365. * the default behavior of the browser. Fixes #4285.
  2366. */
  2367. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  2368. debug("VComboBox: blocking mouseDown event to avoid blur");
  2369. event.preventDefault();
  2370. event.stopPropagation();
  2371. /*
  2372. * In IE the above wont work, the blur event will still trigger. So,
  2373. * we set a flag here to prevent the next blur event from happening.
  2374. * This is not needed if do not already have focus, in that case
  2375. * there will not be any blur event and we should not cancel the
  2376. * next blur.
  2377. */
  2378. if (BrowserInfo.get().isIE() && focused) {
  2379. preventNextBlurEventInIE = true;
  2380. debug("VComboBox: Going to prevent next blur event on IE");
  2381. }
  2382. }
  2383. }
  2384. @Override
  2385. public void onMouseDown(MouseDownEvent event) {
  2386. debug("VComboBox.onMouseDown(): blocking mouseDown event to avoid blur");
  2387. event.preventDefault();
  2388. event.stopPropagation();
  2389. /*
  2390. * In IE the above wont work, the blur event will still trigger. So, we
  2391. * set a flag here to prevent the next blur event from happening. This
  2392. * is not needed if do not already have focus, in that case there will
  2393. * not be any blur event and we should not cancel the next blur.
  2394. */
  2395. if (BrowserInfo.get().isIE() && focused) {
  2396. preventNextBlurEventInIE = true;
  2397. debug("VComboBox: Going to prevent next blur event on IE");
  2398. }
  2399. }
  2400. @Override
  2401. protected void onDetach() {
  2402. super.onDetach();
  2403. suggestionPopup.hide();
  2404. }
  2405. @Override
  2406. public com.google.gwt.user.client.Element getSubPartElement(
  2407. String subPart) {
  2408. String[] parts = subPart.split("/");
  2409. if ("textbox".equals(parts[0])) {
  2410. return tb.getElement();
  2411. } else if ("button".equals(parts[0])) {
  2412. return popupOpener.getElement();
  2413. } else if ("popup".equals(parts[0]) && suggestionPopup.isAttached()) {
  2414. if (parts.length == 2) {
  2415. return suggestionPopup.menu.getSubPartElement(parts[1]);
  2416. }
  2417. return suggestionPopup.getElement();
  2418. }
  2419. return null;
  2420. }
  2421. @Override
  2422. public String getSubPartName(
  2423. com.google.gwt.user.client.Element subElement) {
  2424. if (tb.getElement().isOrHasChild(subElement)) {
  2425. return "textbox";
  2426. } else if (popupOpener.getElement().isOrHasChild(subElement)) {
  2427. return "button";
  2428. } else if (suggestionPopup.getElement().isOrHasChild(subElement)) {
  2429. return "popup";
  2430. }
  2431. return null;
  2432. }
  2433. @Override
  2434. public void setAriaRequired(boolean required) {
  2435. AriaHelper.handleInputRequired(tb, required);
  2436. }
  2437. @Override
  2438. public void setAriaInvalid(boolean invalid) {
  2439. AriaHelper.handleInputInvalid(tb, invalid);
  2440. }
  2441. @Override
  2442. public void bindAriaCaption(
  2443. com.google.gwt.user.client.Element captionElement) {
  2444. AriaHelper.bindCaption(tb, captionElement);
  2445. }
  2446. @Override
  2447. public boolean isWorkPending() {
  2448. return dataReceivedHandler.isWaitingForFilteringResponse()
  2449. || suggestionPopup.lazyPageScroller.isRunning();
  2450. }
  2451. /**
  2452. * Sets the caption of selected item, if "scroll to page" is disabled. This
  2453. * method is meant for internal use and may change in future versions.
  2454. *
  2455. * @since 7.7
  2456. * @param selectedCaption
  2457. * the caption of selected item
  2458. */
  2459. public void setSelectedCaption(String selectedCaption) {
  2460. explicitSelectedCaption = selectedCaption;
  2461. if (selectedCaption != null) {
  2462. setText(selectedCaption);
  2463. }
  2464. }
  2465. /**
  2466. * This method is meant for internal use and may change in future versions.
  2467. *
  2468. * @since 7.7
  2469. * @return the caption of selected item, if "scroll to page" is disabled
  2470. */
  2471. public String getSelectedCaption() {
  2472. return explicitSelectedCaption;
  2473. }
  2474. /**
  2475. * Returns a handler receiving notifications from the connector about
  2476. * communications.
  2477. *
  2478. * @return the dataReceivedHandler
  2479. */
  2480. public DataReceivedHandler getDataReceivedHandler() {
  2481. return dataReceivedHandler;
  2482. }
  2483. /**
  2484. * Sets the number of items to show per page, or 0 for showing all items.
  2485. *
  2486. * @param pageLength
  2487. * new page length or 0 for all items
  2488. */
  2489. public void setPageLength(int pageLength) {
  2490. this.pageLength = pageLength;
  2491. }
  2492. /**
  2493. * Sets the suggestion pop-up's width as a CSS string. By using relative
  2494. * units (e.g. "50%") it's possible to set the popup's width relative to the
  2495. * ComboBox itself.
  2496. *
  2497. * @param suggestionPopupWidth
  2498. * new popup width as CSS string, null for old default width
  2499. * calculation based on items
  2500. */
  2501. public void setSuggestionPopupWidth(String suggestionPopupWidth) {
  2502. this.suggestionPopupWidth = suggestionPopupWidth;
  2503. }
  2504. /**
  2505. * Sets whether creation of new items when there is no match is allowed or
  2506. * not.
  2507. *
  2508. * @param allowNewItems
  2509. * true to allow creation of new items, false to only allow
  2510. * selection of existing items
  2511. */
  2512. public void setAllowNewItems(boolean allowNewItems) {
  2513. this.allowNewItems = allowNewItems;
  2514. }
  2515. /**
  2516. * Sets the total number of suggestions.
  2517. * <p>
  2518. * NOTE: this excluded the possible null selection item!
  2519. * <p>
  2520. * NOTE: this just updates the state, but doesn't update any UI.
  2521. *
  2522. * @since 8.0
  2523. * @param totalSuggestions
  2524. * total number of suggestions
  2525. */
  2526. public void setTotalSuggestions(int totalSuggestions) {
  2527. this.totalSuggestions = totalSuggestions;
  2528. }
  2529. /**
  2530. * Gets the total number of suggestions, excluding the null selection item.
  2531. *
  2532. * @since 8.0
  2533. * @return total number of suggestions
  2534. */
  2535. public int getTotalSuggestions() {
  2536. return totalSuggestions;
  2537. }
  2538. /**
  2539. * Gets the total number of suggestions, including the possible null
  2540. * selection item, if it should be visible.
  2541. *
  2542. * @return total number of suggestions with null selection items
  2543. */
  2544. private int getTotalSuggestionsIncludingNullSelectionItem() {
  2545. return getTotalSuggestions()
  2546. + (getNullSelectionItemShouldBeVisible() ? 1 : 0);
  2547. }
  2548. /**
  2549. * Returns null selection item should be visible or not.
  2550. * <p>
  2551. * NOTE: this checks for any entered filter value, and whether the feature
  2552. * is enabled
  2553. *
  2554. * @since 8.0
  2555. * @return {@code true} if it should be visible, {@code}
  2556. */
  2557. public boolean getNullSelectionItemShouldBeVisible() {
  2558. return nullSelectionAllowed && "".equals(lastFilter);
  2559. }
  2560. /**
  2561. * Gets the empty selection caption.
  2562. *
  2563. * @since 8.0.7
  2564. * @return the empty selection caption
  2565. */
  2566. public String getEmptySelectionCaption() {
  2567. return emptySelectionCaption;
  2568. }
  2569. /**
  2570. * Sets the empty selection caption for this VComboBox. The text is
  2571. * displayed in the text input when nothing is selected.
  2572. *
  2573. * @param emptySelectionCaption
  2574. * the empty selection caption
  2575. *
  2576. * @since 8.0.7
  2577. */
  2578. public void setEmptySelectionCaption(String emptySelectionCaption) {
  2579. this.emptySelectionCaption = emptySelectionCaption;
  2580. if (selectedOptionKey == null) {
  2581. setText(emptySelectionCaption);
  2582. }
  2583. }
  2584. private static Logger getLogger() {
  2585. return Logger.getLogger(VComboBox.class.getName());
  2586. }
  2587. }