You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VFilterSelect.java 95KB

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