Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

VFilterSelect.java 95KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727
  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. getElement().setAttribute("autocomplete", Math.random() + "");
  1254. }
  1255. /**
  1256. * Overridden to avoid selecting text when text input is disabled.
  1257. */
  1258. @Override
  1259. public void setSelectionRange(int pos, int length) {
  1260. if (textInputEnabled) {
  1261. /*
  1262. * set selection range with a backwards direction: anchor at the
  1263. * back, focus at the front. This means that items that are too
  1264. * long to display will display from the start and not the end
  1265. * even on Firefox.
  1266. *
  1267. * We need the JSNI function to set selection range so that we
  1268. * can use the optional direction attribute to set the anchor to
  1269. * the end and the focus to the start. This makes Firefox work
  1270. * the same way as other browsers (#13477)
  1271. */
  1272. WidgetUtil.setSelectionRange(getElement(), pos, length,
  1273. "backward");
  1274. } else {
  1275. /*
  1276. * Setting the selectionrange for an uneditable textbox leads to
  1277. * unwanted behavior when the width of the textbox is narrower
  1278. * than the width of the entry: the end of the entry is shown
  1279. * instead of the beginning. (see #13477)
  1280. *
  1281. * To avoid this, we set the caret to the beginning of the line.
  1282. */
  1283. super.setSelectionRange(0, 0);
  1284. }
  1285. }
  1286. }
  1287. @Deprecated
  1288. public static final FilteringMode FILTERINGMODE_OFF = FilteringMode.OFF;
  1289. @Deprecated
  1290. public static final FilteringMode FILTERINGMODE_STARTSWITH = FilteringMode.STARTSWITH;
  1291. @Deprecated
  1292. public static final FilteringMode FILTERINGMODE_CONTAINS = FilteringMode.CONTAINS;
  1293. public static final String CLASSNAME = "v-filterselect";
  1294. private static final String STYLE_NO_INPUT = "no-input";
  1295. /** For internal use only. May be removed or replaced in the future. */
  1296. public int pageLength = 10;
  1297. private boolean enableDebug = false;
  1298. private final FlowPanel panel = new FlowPanel();
  1299. /**
  1300. * The text box where the filter is written
  1301. * <p>
  1302. * For internal use only. May be removed or replaced in the future.
  1303. */
  1304. public final TextBox tb;
  1305. /** For internal use only. May be removed or replaced in the future. */
  1306. public final SuggestionPopup suggestionPopup;
  1307. /**
  1308. * Used when measuring the width of the popup
  1309. */
  1310. private final HTML popupOpener = new HTML("") {
  1311. /*
  1312. * (non-Javadoc)
  1313. *
  1314. * @see
  1315. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt
  1316. * .user.client.Event)
  1317. */
  1318. @Override
  1319. public void onBrowserEvent(Event event) {
  1320. super.onBrowserEvent(event);
  1321. /*
  1322. * Prevent the keyboard focus from leaving the textfield by
  1323. * preventing the default behavior of the browser. Fixes #4285.
  1324. */
  1325. handleMouseDownEvent(event);
  1326. }
  1327. };
  1328. private class IconWidget extends Widget {
  1329. private Icon icon;
  1330. IconWidget(Icon icon) {
  1331. this.icon = icon;
  1332. setElement(icon.getElement());
  1333. addDomHandler(VFilterSelect.this, ClickEvent.getType());
  1334. }
  1335. }
  1336. private IconWidget selectedItemIcon;
  1337. /** For internal use only. May be removed or replaced in the future. */
  1338. public ApplicationConnection client;
  1339. /** For internal use only. May be removed or replaced in the future. */
  1340. public String paintableId;
  1341. /** For internal use only. May be removed or replaced in the future. */
  1342. public int currentPage;
  1343. /**
  1344. * A collection of available suggestions (options) as received from the
  1345. * server.
  1346. * <p>
  1347. * For internal use only. May be removed or replaced in the future.
  1348. */
  1349. public final List<FilterSelectSuggestion> currentSuggestions = new ArrayList<FilterSelectSuggestion>();
  1350. /** For internal use only. May be removed or replaced in the future. */
  1351. public boolean immediate;
  1352. /** For internal use only. May be removed or replaced in the future. */
  1353. public String selectedOptionKey;
  1354. /** For internal use only. May be removed or replaced in the future. */
  1355. public boolean waitingForFilteringResponse = false;
  1356. /** For internal use only. May be removed or replaced in the future. */
  1357. public boolean updateSelectionWhenReponseIsReceived = false;
  1358. /** For internal use only. May be removed or replaced in the future. */
  1359. public boolean initDone = false;
  1360. /** For internal use only. May be removed or replaced in the future. */
  1361. public String lastFilter = "";
  1362. /** For internal use only. May be removed or replaced in the future. */
  1363. public enum Select {
  1364. NONE, FIRST, LAST
  1365. }
  1366. /** For internal use only. May be removed or replaced in the future. */
  1367. public Select selectPopupItemWhenResponseIsReceived = Select.NONE;
  1368. /**
  1369. * The current suggestion selected from the dropdown. This is one of the
  1370. * values in currentSuggestions except when filtering, in this case
  1371. * currentSuggestion might not be in currentSuggestions.
  1372. * <p>
  1373. * For internal use only. May be removed or replaced in the future.
  1374. */
  1375. public FilterSelectSuggestion currentSuggestion;
  1376. /** For internal use only. May be removed or replaced in the future. */
  1377. public boolean allowNewItem;
  1378. /** For internal use only. May be removed or replaced in the future. */
  1379. public int totalMatches;
  1380. /** For internal use only. May be removed or replaced in the future. */
  1381. public boolean nullSelectionAllowed;
  1382. /** For internal use only. May be removed or replaced in the future. */
  1383. public boolean nullSelectItem;
  1384. /** For internal use only. May be removed or replaced in the future. */
  1385. public boolean enabled;
  1386. /** For internal use only. May be removed or replaced in the future. */
  1387. public boolean readonly;
  1388. /** For internal use only. May be removed or replaced in the future. */
  1389. public FilteringMode filteringmode = FilteringMode.OFF;
  1390. // shown in unfocused empty field, disappears on focus (e.g "Search here")
  1391. private static final String CLASSNAME_PROMPT = "prompt";
  1392. /** For internal use only. May be removed or replaced in the future. */
  1393. public String inputPrompt = "";
  1394. /** For internal use only. May be removed or replaced in the future. */
  1395. public boolean prompting = false;
  1396. /**
  1397. * Set true when popupopened has been clicked. Cleared on each UIDL-update.
  1398. * This handles the special case where are not filtering yet and the
  1399. * selected value has changed on the server-side. See #2119
  1400. * <p>
  1401. * For internal use only. May be removed or replaced in the future.
  1402. */
  1403. public boolean popupOpenerClicked;
  1404. /** For internal use only. May be removed or replaced in the future. */
  1405. public int suggestionPopupMinWidth = 0;
  1406. public String suggestionPopupWidth = null;
  1407. private int popupWidth = -1;
  1408. /**
  1409. * Stores the last new item string to avoid double submissions. Cleared on
  1410. * uidl updates.
  1411. * <p>
  1412. * For internal use only. May be removed or replaced in the future.
  1413. */
  1414. public String lastNewItemString;
  1415. /** For internal use only. May be removed or replaced in the future. */
  1416. public boolean focused = false;
  1417. /**
  1418. * If set to false, the component should not allow entering text to the
  1419. * field even for filtering.
  1420. */
  1421. private boolean textInputEnabled = true;
  1422. /**
  1423. * Default constructor.
  1424. */
  1425. public VFilterSelect() {
  1426. tb = createTextBox();
  1427. suggestionPopup = createSuggestionPopup();
  1428. popupOpener.sinkEvents(Event.ONMOUSEDOWN);
  1429. Roles.getButtonRole().setAriaHiddenState(popupOpener.getElement(),
  1430. true);
  1431. Roles.getButtonRole().set(popupOpener.getElement());
  1432. panel.add(tb);
  1433. panel.add(popupOpener);
  1434. initWidget(panel);
  1435. Roles.getComboboxRole().set(panel.getElement());
  1436. tb.addKeyDownHandler(this);
  1437. tb.addKeyUpHandler(this);
  1438. tb.addFocusHandler(this);
  1439. tb.addBlurHandler(this);
  1440. tb.addClickHandler(this);
  1441. popupOpener.addClickHandler(this);
  1442. setStyleName(CLASSNAME);
  1443. sinkEvents(Event.ONPASTE);
  1444. }
  1445. private static double getMarginBorderPaddingWidth(Element element) {
  1446. final ComputedStyle s = new ComputedStyle(element);
  1447. return s.getMarginWidth() + s.getBorderWidth() + s.getPaddingWidth();
  1448. }
  1449. /*
  1450. * (non-Javadoc)
  1451. *
  1452. * @see
  1453. * com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt
  1454. * .user.client.Event)
  1455. */
  1456. @Override
  1457. public void onBrowserEvent(Event event) {
  1458. super.onBrowserEvent(event);
  1459. if (event.getTypeInt() == Event.ONPASTE) {
  1460. if (textInputEnabled) {
  1461. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  1462. @Override
  1463. public void execute() {
  1464. filterOptions(currentPage);
  1465. }
  1466. });
  1467. }
  1468. }
  1469. }
  1470. /**
  1471. * This method will create the TextBox used by the VFilterSelect instance.
  1472. * It is invoked during the Constructor and should only be overridden if a
  1473. * custom TextBox shall be used. The overriding method cannot use any
  1474. * instance variables.
  1475. *
  1476. * @since 7.1.5
  1477. * @return TextBox instance used by this VFilterSelect
  1478. */
  1479. protected TextBox createTextBox() {
  1480. return new FilterSelectTextBox();
  1481. }
  1482. /**
  1483. * This method will create the SuggestionPopup used by the VFilterSelect
  1484. * instance. It is invoked during the Constructor and should only be
  1485. * overridden if a custom SuggestionPopup shall be used. The overriding
  1486. * method cannot use any instance variables.
  1487. *
  1488. * @since 7.1.5
  1489. * @return SuggestionPopup instance used by this VFilterSelect
  1490. */
  1491. protected SuggestionPopup createSuggestionPopup() {
  1492. return new SuggestionPopup();
  1493. }
  1494. @Override
  1495. public void setStyleName(String style) {
  1496. super.setStyleName(style);
  1497. updateStyleNames();
  1498. }
  1499. @Override
  1500. public void setStylePrimaryName(String style) {
  1501. super.setStylePrimaryName(style);
  1502. updateStyleNames();
  1503. }
  1504. protected void updateStyleNames() {
  1505. tb.setStyleName(getStylePrimaryName() + "-input");
  1506. popupOpener.setStyleName(getStylePrimaryName() + "-button");
  1507. suggestionPopup.setStyleName(getStylePrimaryName() + "-suggestpopup");
  1508. }
  1509. /**
  1510. * Does the Select have more pages?
  1511. *
  1512. * @return true if a next page exists, else false if the current page is the
  1513. * last page
  1514. */
  1515. public boolean hasNextPage() {
  1516. return pageLength > 0 && totalMatches > (currentPage + 1) * pageLength;
  1517. }
  1518. /**
  1519. * Filters the options at a certain page. Uses the text box input as a
  1520. * filter
  1521. *
  1522. * @param page
  1523. * The page which items are to be filtered
  1524. */
  1525. public void filterOptions(int page) {
  1526. filterOptions(page, tb.getText());
  1527. }
  1528. /**
  1529. * Filters the options at certain page using the given filter.
  1530. *
  1531. * @param page
  1532. * The page to filter
  1533. * @param filter
  1534. * The filter to apply to the components
  1535. */
  1536. public void filterOptions(int page, String filter) {
  1537. filterOptions(page, filter, true);
  1538. }
  1539. /**
  1540. * Filters the options at certain page using the given filter
  1541. *
  1542. * @param page
  1543. * The page to filter
  1544. * @param filter
  1545. * The filter to apply to the options
  1546. * @param immediate
  1547. * Whether to send the options request immediately
  1548. */
  1549. private void filterOptions(int page, String filter, boolean immediate) {
  1550. debug("VFS: filterOptions(" + page + ", " + filter + ", " + immediate
  1551. + ")");
  1552. if (filter.equals(lastFilter) && currentPage == page) {
  1553. if (!suggestionPopup.isAttached()) {
  1554. suggestionPopup.showSuggestions(currentSuggestions, currentPage,
  1555. totalMatches);
  1556. }
  1557. return;
  1558. }
  1559. if (!filter.equals(lastFilter)) {
  1560. // when filtering, let the server decide the page unless we've
  1561. // set the filter to empty and explicitly said that we want to see
  1562. // the results starting from page 0.
  1563. if ("".equals(filter) && page != 0) {
  1564. // let server decide
  1565. page = -1;
  1566. } else {
  1567. page = 0;
  1568. }
  1569. }
  1570. waitingForFilteringResponse = true;
  1571. client.updateVariable(paintableId, "filter", filter, false);
  1572. client.updateVariable(paintableId, "page", page, immediate);
  1573. afterUpdateClientVariables();
  1574. lastFilter = filter;
  1575. currentPage = page;
  1576. }
  1577. /** For internal use only. May be removed or replaced in the future. */
  1578. public void updateReadOnly() {
  1579. debug("VFS: updateReadOnly()");
  1580. tb.setReadOnly(readonly || !textInputEnabled);
  1581. }
  1582. public void setTextInputEnabled(boolean textInputEnabled) {
  1583. debug("VFS: setTextInputEnabled()");
  1584. // Always update styles as they might have been overwritten
  1585. if (textInputEnabled) {
  1586. removeStyleDependentName(STYLE_NO_INPUT);
  1587. Roles.getTextboxRole().removeAriaReadonlyProperty(tb.getElement());
  1588. } else {
  1589. addStyleDependentName(STYLE_NO_INPUT);
  1590. Roles.getTextboxRole().setAriaReadonlyProperty(tb.getElement(),
  1591. true);
  1592. }
  1593. if (this.textInputEnabled == textInputEnabled) {
  1594. return;
  1595. }
  1596. this.textInputEnabled = textInputEnabled;
  1597. updateReadOnly();
  1598. }
  1599. /**
  1600. * Sets the text in the text box.
  1601. *
  1602. * @param text
  1603. * the text to set in the text box
  1604. */
  1605. public void setTextboxText(final String text) {
  1606. if (enableDebug) {
  1607. debug("VFS: setTextboxText(" + text + ")");
  1608. }
  1609. setText(text);
  1610. }
  1611. private void setText(final String text) {
  1612. /**
  1613. * To leave caret in the beginning of the line. SetSelectionRange
  1614. * wouldn't work on IE (see #13477)
  1615. */
  1616. Direction previousDirection = tb.getDirection();
  1617. tb.setDirection(Direction.RTL);
  1618. tb.setText(text);
  1619. tb.setDirection(previousDirection);
  1620. }
  1621. /**
  1622. * Turns prompting on. When prompting is turned on a command prompt is shown
  1623. * in the text box if nothing has been entered.
  1624. */
  1625. public void setPromptingOn() {
  1626. debug("VFS: setPromptingOn()");
  1627. if (!prompting) {
  1628. prompting = true;
  1629. addStyleDependentName(CLASSNAME_PROMPT);
  1630. }
  1631. setTextboxText(inputPrompt);
  1632. }
  1633. /**
  1634. * Turns prompting off. When prompting is turned on a command prompt is
  1635. * shown in the text box if nothing has been entered.
  1636. * <p>
  1637. * For internal use only. May be removed or replaced in the future.
  1638. *
  1639. * @param text
  1640. * The text the text box should contain.
  1641. */
  1642. public void setPromptingOff(String text) {
  1643. debug("VFS: setPromptingOff()");
  1644. setTextboxText(text);
  1645. if (prompting) {
  1646. prompting = false;
  1647. removeStyleDependentName(CLASSNAME_PROMPT);
  1648. }
  1649. }
  1650. /**
  1651. * Triggered when a suggestion is selected.
  1652. *
  1653. * @param suggestion
  1654. * The suggestion that just got selected.
  1655. */
  1656. public void onSuggestionSelected(FilterSelectSuggestion suggestion) {
  1657. if (enableDebug) {
  1658. debug("VFS: onSuggestionSelected(" + suggestion.caption + ": "
  1659. + suggestion.key + ")");
  1660. }
  1661. updateSelectionWhenReponseIsReceived = false;
  1662. currentSuggestion = suggestion;
  1663. String newKey;
  1664. if (suggestion.key.equals("")) {
  1665. // "nullselection"
  1666. newKey = "";
  1667. } else {
  1668. // normal selection
  1669. newKey = suggestion.getOptionKey();
  1670. }
  1671. String text = suggestion.getReplacementString();
  1672. if ("".equals(newKey) && !focused) {
  1673. setPromptingOn();
  1674. } else {
  1675. setPromptingOff(text);
  1676. }
  1677. setSelectedItemIcon(suggestion.getIconUri());
  1678. if (!(newKey.equals(selectedOptionKey)
  1679. || ("".equals(newKey) && selectedOptionKey == null))) {
  1680. selectedOptionKey = newKey;
  1681. client.updateVariable(paintableId, "selected",
  1682. new String[] { selectedOptionKey }, immediate);
  1683. afterUpdateClientVariables();
  1684. // currentPage = -1; // forget the page
  1685. }
  1686. if (getSelectedCaption() != null && newKey.equals("")) {
  1687. // In scrollToPage(false) mode selecting null seems to be broken
  1688. // if current selection is not on first page. The above clause is so
  1689. // hard to interpret that new clause added here :-(
  1690. selectedOptionKey = newKey;
  1691. explicitSelectedCaption = null;
  1692. client.updateVariable(paintableId, "selected",
  1693. new String[] { selectedOptionKey }, immediate);
  1694. afterUpdateClientVariables();
  1695. }
  1696. suggestionPopup.hide();
  1697. }
  1698. /**
  1699. * Sets the icon URI of the selected item. The icon is shown on the left
  1700. * side of the item caption text. Set the URI to null to remove the icon.
  1701. *
  1702. * @param iconUri
  1703. * The URI of the icon
  1704. */
  1705. public void setSelectedItemIcon(String iconUri) {
  1706. if (iconUri == null || iconUri.isEmpty()) {
  1707. if (selectedItemIcon != null) {
  1708. panel.remove(selectedItemIcon);
  1709. selectedItemIcon = null;
  1710. afterSelectedItemIconChange();
  1711. }
  1712. } else {
  1713. IconWidget newIcon = new IconWidget(client.getIcon(iconUri));
  1714. if (iconEquals(newIcon, selectedItemIcon)) {
  1715. /*
  1716. * Do not update the icon if nothing has changed. Otherwise we
  1717. * can cause problems such as not being able to click in the
  1718. * icon to open the popup (blur might occur and call this
  1719. * method, icon is replaced and the click event is not delivered
  1720. * to the new icon)
  1721. */
  1722. return;
  1723. }
  1724. if (selectedItemIcon != null) {
  1725. panel.remove(selectedItemIcon);
  1726. }
  1727. // Older IE versions don't scale icon correctly if DOM
  1728. // contains height and width attributes.
  1729. newIcon.getElement().removeAttribute("height");
  1730. newIcon.getElement().removeAttribute("width");
  1731. newIcon.addDomHandler(new LoadHandler() {
  1732. @Override
  1733. public void onLoad(LoadEvent event) {
  1734. afterSelectedItemIconChange();
  1735. }
  1736. }, LoadEvent.getType());
  1737. panel.insert(newIcon, 0);
  1738. selectedItemIcon = newIcon;
  1739. afterSelectedItemIconChange();
  1740. }
  1741. }
  1742. /**
  1743. * Checks if the icon widgets show the same icon.
  1744. *
  1745. * @param icon1
  1746. * the first widget
  1747. * @param icon2
  1748. * the second widget
  1749. * @return <code>true</code> if they show the same icon, <code>false</code>
  1750. * otherwise
  1751. */
  1752. private static boolean iconEquals(IconWidget icon1, IconWidget icon2) {
  1753. if (icon1 == null) {
  1754. return icon2 == null;
  1755. } else if (icon2 == null) {
  1756. return false;
  1757. } else {
  1758. return icon1.icon.getUri().equals(icon2.icon.getUri());
  1759. }
  1760. }
  1761. private void afterSelectedItemIconChange() {
  1762. if (BrowserInfo.get().isWebkit() || BrowserInfo.get().isIE8()) {
  1763. // Some browsers need a nudge to reposition the text field
  1764. forceReflow();
  1765. }
  1766. updateRootWidth();
  1767. if (selectedItemIcon != null) {
  1768. updateSelectedIconPosition();
  1769. }
  1770. }
  1771. private void forceReflow() {
  1772. WidgetUtil.setStyleTemporarily(tb.getElement(), "zoom", "1");
  1773. }
  1774. /**
  1775. * Positions the icon vertically in the middle. Should be called after the
  1776. * icon has loaded
  1777. */
  1778. private void updateSelectedIconPosition() {
  1779. // Position icon vertically to middle
  1780. int availableHeight = 0;
  1781. availableHeight = getOffsetHeight();
  1782. int iconHeight = WidgetUtil.getRequiredHeight(selectedItemIcon);
  1783. int marginTop = (availableHeight - iconHeight) / 2;
  1784. selectedItemIcon.getElement().getStyle().setMarginTop(marginTop,
  1785. Unit.PX);
  1786. }
  1787. private static Set<Integer> navigationKeyCodes = new HashSet<Integer>();
  1788. static {
  1789. navigationKeyCodes.add(KeyCodes.KEY_DOWN);
  1790. navigationKeyCodes.add(KeyCodes.KEY_UP);
  1791. navigationKeyCodes.add(KeyCodes.KEY_PAGEDOWN);
  1792. navigationKeyCodes.add(KeyCodes.KEY_PAGEUP);
  1793. navigationKeyCodes.add(KeyCodes.KEY_ENTER);
  1794. }
  1795. /*
  1796. * (non-Javadoc)
  1797. *
  1798. * @see
  1799. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1800. * .event.dom.client.KeyDownEvent)
  1801. */
  1802. @Override
  1803. public void onKeyDown(KeyDownEvent event) {
  1804. if (enabled && !readonly) {
  1805. int keyCode = event.getNativeKeyCode();
  1806. if (enableDebug) {
  1807. debug("VFS: key down: " + keyCode);
  1808. }
  1809. if (waitingForFilteringResponse
  1810. && navigationKeyCodes.contains(keyCode)) {
  1811. /*
  1812. * Keyboard navigation events should not be handled while we are
  1813. * waiting for a response. This avoids flickering, disappearing
  1814. * items, wrongly interpreted responses and more.
  1815. */
  1816. if (enableDebug) {
  1817. debug("Ignoring " + keyCode
  1818. + " because we are waiting for a filtering response");
  1819. }
  1820. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1821. event.stopPropagation();
  1822. return;
  1823. }
  1824. if (suggestionPopup.isAttached()) {
  1825. if (enableDebug) {
  1826. debug("Keycode " + keyCode + " target is popup");
  1827. }
  1828. popupKeyDown(event);
  1829. } else {
  1830. if (enableDebug) {
  1831. debug("Keycode " + keyCode + " target is text field");
  1832. }
  1833. inputFieldKeyDown(event);
  1834. }
  1835. }
  1836. }
  1837. private void debug(String string) {
  1838. if (enableDebug) {
  1839. getLogger().severe(string);
  1840. }
  1841. }
  1842. /**
  1843. * Triggered when a key is pressed in the text box
  1844. *
  1845. * @param event
  1846. * The KeyDownEvent
  1847. */
  1848. private void inputFieldKeyDown(KeyDownEvent event) {
  1849. if (enableDebug) {
  1850. debug("VFS: inputFieldKeyDown(" + event.getNativeKeyCode() + ")");
  1851. }
  1852. switch (event.getNativeKeyCode()) {
  1853. case KeyCodes.KEY_DOWN:
  1854. case KeyCodes.KEY_UP:
  1855. case KeyCodes.KEY_PAGEDOWN:
  1856. case KeyCodes.KEY_PAGEUP:
  1857. // open popup as from gadget
  1858. filterOptions(-1, "");
  1859. lastFilter = "";
  1860. tb.selectAll();
  1861. break;
  1862. case KeyCodes.KEY_ENTER:
  1863. /*
  1864. * This only handles the case when new items is allowed, a text is
  1865. * entered, the popup opener button is clicked to close the popup
  1866. * and enter is then pressed (see #7560).
  1867. */
  1868. if (!allowNewItem) {
  1869. return;
  1870. }
  1871. if (currentSuggestion != null && tb.getText()
  1872. .equals(currentSuggestion.getReplacementString())) {
  1873. // Retain behavior from #6686 by returning without stopping
  1874. // propagation if there's nothing to do
  1875. return;
  1876. }
  1877. suggestionPopup.menu.doSelectedItemAction();
  1878. event.stopPropagation();
  1879. break;
  1880. }
  1881. }
  1882. /**
  1883. * Triggered when a key was pressed in the suggestion popup.
  1884. *
  1885. * @param event
  1886. * The KeyDownEvent of the key
  1887. */
  1888. private void popupKeyDown(KeyDownEvent event) {
  1889. if (enableDebug) {
  1890. debug("VFS: popupKeyDown(" + event.getNativeKeyCode() + ")");
  1891. }
  1892. // Propagation of handled events is stopped so other handlers such as
  1893. // shortcut key handlers do not also handle the same events.
  1894. switch (event.getNativeKeyCode()) {
  1895. case KeyCodes.KEY_DOWN:
  1896. suggestionPopup.selectNextItem();
  1897. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1898. event.stopPropagation();
  1899. break;
  1900. case KeyCodes.KEY_UP:
  1901. suggestionPopup.selectPrevItem();
  1902. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1903. event.stopPropagation();
  1904. break;
  1905. case KeyCodes.KEY_PAGEDOWN:
  1906. selectNextPage();
  1907. event.stopPropagation();
  1908. break;
  1909. case KeyCodes.KEY_PAGEUP:
  1910. selectPrevPage();
  1911. event.stopPropagation();
  1912. break;
  1913. case KeyCodes.KEY_ESCAPE:
  1914. reset();
  1915. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1916. event.stopPropagation();
  1917. break;
  1918. case KeyCodes.KEY_TAB:
  1919. case KeyCodes.KEY_ENTER:
  1920. if (!allowNewItem) {
  1921. int selected = suggestionPopup.menu.getSelectedIndex();
  1922. if (selected != -1) {
  1923. onSuggestionSelected(currentSuggestions.get(selected));
  1924. } else {
  1925. // The way VFilterSelect is done, it handles enter and tab
  1926. // in exactly the same way so we close the popup in both
  1927. // cases even though we could leave it open when pressing
  1928. // enter
  1929. suggestionPopup.hide();
  1930. }
  1931. } else {
  1932. // Handle addition of new items.
  1933. suggestionPopup.menu.doSelectedItemAction();
  1934. }
  1935. event.stopPropagation();
  1936. break;
  1937. }
  1938. }
  1939. /*
  1940. * Show the prev page.
  1941. */
  1942. private void selectPrevPage() {
  1943. if (currentPage > 0) {
  1944. filterOptions(currentPage - 1, lastFilter);
  1945. selectPopupItemWhenResponseIsReceived = Select.LAST;
  1946. }
  1947. }
  1948. /*
  1949. * Show the next page.
  1950. */
  1951. private void selectNextPage() {
  1952. if (hasNextPage()) {
  1953. filterOptions(currentPage + 1, lastFilter);
  1954. selectPopupItemWhenResponseIsReceived = Select.FIRST;
  1955. }
  1956. }
  1957. /**
  1958. * Triggered when a key was depressed.
  1959. *
  1960. * @param event
  1961. * The KeyUpEvent of the key depressed
  1962. */
  1963. @Override
  1964. public void onKeyUp(KeyUpEvent event) {
  1965. if (enableDebug) {
  1966. debug("VFS: onKeyUp(" + event.getNativeKeyCode() + ")");
  1967. }
  1968. if (enabled && !readonly) {
  1969. switch (event.getNativeKeyCode()) {
  1970. case KeyCodes.KEY_ENTER:
  1971. case KeyCodes.KEY_TAB:
  1972. case KeyCodes.KEY_SHIFT:
  1973. case KeyCodes.KEY_CTRL:
  1974. case KeyCodes.KEY_ALT:
  1975. case KeyCodes.KEY_DOWN:
  1976. case KeyCodes.KEY_UP:
  1977. case KeyCodes.KEY_PAGEDOWN:
  1978. case KeyCodes.KEY_PAGEUP:
  1979. case KeyCodes.KEY_ESCAPE:
  1980. // NOP
  1981. break;
  1982. default:
  1983. if (textInputEnabled) {
  1984. // when filtering, we always want to see the results on the
  1985. // first page first.
  1986. filterOptions(0);
  1987. }
  1988. break;
  1989. }
  1990. }
  1991. }
  1992. /**
  1993. * Resets the Select to its initial state
  1994. */
  1995. private void reset() {
  1996. debug("VFS: reset()");
  1997. if (currentSuggestion != null) {
  1998. String text = currentSuggestion.getReplacementString();
  1999. setPromptingOff(text);
  2000. setSelectedItemIcon(currentSuggestion.getIconUri());
  2001. selectedOptionKey = currentSuggestion.key;
  2002. } else {
  2003. if (focused || readonly || !enabled) {
  2004. setPromptingOff("");
  2005. } else {
  2006. setPromptingOn();
  2007. }
  2008. setSelectedItemIcon(null);
  2009. selectedOptionKey = null;
  2010. }
  2011. lastFilter = "";
  2012. suggestionPopup.hide();
  2013. }
  2014. /**
  2015. * Listener for popupopener.
  2016. */
  2017. @Override
  2018. public void onClick(ClickEvent event) {
  2019. debug("VFS: onClick()");
  2020. if (textInputEnabled && event.getNativeEvent().getEventTarget()
  2021. .cast() == tb.getElement()) {
  2022. // Don't process clicks on the text field if text input is enabled
  2023. return;
  2024. }
  2025. if (enabled && !readonly) {
  2026. // ask suggestionPopup if it was just closed, we are using GWT
  2027. // Popup's auto close feature
  2028. if (!suggestionPopup.isJustClosed()) {
  2029. // If a focus event is not going to be sent, send the options
  2030. // request immediately; otherwise queue in the same burst as the
  2031. // focus event. Fixes #8321.
  2032. boolean immediate = focused
  2033. || !client.hasEventListeners(this, EventId.FOCUS);
  2034. filterOptions(-1, "", immediate);
  2035. popupOpenerClicked = true;
  2036. lastFilter = "";
  2037. }
  2038. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  2039. focus();
  2040. tb.selectAll();
  2041. }
  2042. }
  2043. /**
  2044. * Update minimum width for FilterSelect textarea based on input prompt and
  2045. * suggestions.
  2046. * <p>
  2047. * For internal use only. May be removed or replaced in the future.
  2048. */
  2049. public void updateSuggestionPopupMinWidth() {
  2050. // used only to calculate minimum width
  2051. String captions = WidgetUtil.escapeHTML(inputPrompt);
  2052. for (FilterSelectSuggestion suggestion : currentSuggestions) {
  2053. // Collect captions so we can calculate minimum width for
  2054. // textarea
  2055. if (!captions.isEmpty()) {
  2056. captions += "|";
  2057. }
  2058. captions += WidgetUtil
  2059. .escapeHTML(suggestion.getReplacementString());
  2060. }
  2061. // Calculate minimum textarea width
  2062. suggestionPopupMinWidth = minWidth(captions);
  2063. }
  2064. /**
  2065. * Calculate minimum width for FilterSelect textarea.
  2066. * <p>
  2067. * For internal use only. May be removed or replaced in the future.
  2068. */
  2069. public native int minWidth(String captions)
  2070. /*-{
  2071. if (!captions || captions.length <= 0)
  2072. return 0;
  2073. captions = captions.split("|");
  2074. var d = $wnd.document.createElement("div");
  2075. var html = "";
  2076. for (var i=0; i < captions.length; i++) {
  2077. html += "<div>" + captions[i] + "</div>";
  2078. // TODO apply same CSS classname as in suggestionmenu
  2079. }
  2080. d.style.position = "absolute";
  2081. d.style.top = "0";
  2082. d.style.left = "0";
  2083. d.style.visibility = "hidden";
  2084. d.innerHTML = html;
  2085. $wnd.document.body.appendChild(d);
  2086. var w = d.offsetWidth;
  2087. $wnd.document.body.removeChild(d);
  2088. return w;
  2089. }-*/;
  2090. /**
  2091. * A flag which prevents a focus event from taking place
  2092. */
  2093. boolean iePreventNextFocus = false;
  2094. /*
  2095. * (non-Javadoc)
  2096. *
  2097. * @see
  2098. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  2099. * .dom.client.FocusEvent)
  2100. */
  2101. @Override
  2102. public void onFocus(FocusEvent event) {
  2103. debug("VFS: onFocus()");
  2104. /*
  2105. * When we disable a blur event in ie we need to refocus the textfield.
  2106. * This will cause a focus event we do not want to process, so in that
  2107. * case we just ignore it.
  2108. */
  2109. if (BrowserInfo.get().isIE() && iePreventNextFocus) {
  2110. iePreventNextFocus = false;
  2111. return;
  2112. }
  2113. focused = true;
  2114. if (prompting && !readonly) {
  2115. setPromptingOff("");
  2116. }
  2117. addStyleDependentName("focus");
  2118. if (client.hasEventListeners(this, EventId.FOCUS)) {
  2119. client.updateVariable(paintableId, EventId.FOCUS, "", true);
  2120. afterUpdateClientVariables();
  2121. }
  2122. ComponentConnector connector = ConnectorMap.get(client)
  2123. .getConnector(this);
  2124. client.getVTooltip()
  2125. .showAssistive(connector.getTooltipInfo(getElement()));
  2126. }
  2127. /**
  2128. * A flag which cancels the blur event and sets the focus back to the
  2129. * textfield if the Browser is IE
  2130. */
  2131. boolean preventNextBlurEventInIE = false;
  2132. private String explicitSelectedCaption;
  2133. /*
  2134. * (non-Javadoc)
  2135. *
  2136. * @see
  2137. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  2138. * .dom.client.BlurEvent)
  2139. */
  2140. @Override
  2141. public void onBlur(BlurEvent event) {
  2142. debug("VFS: onBlur()");
  2143. if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) {
  2144. /*
  2145. * Clicking in the suggestion popup or on the popup button in IE
  2146. * causes a blur event to be sent for the field. In other browsers
  2147. * this is prevented by canceling/preventing default behavior for
  2148. * the focus event, in IE we handle it here by refocusing the text
  2149. * field and ignoring the resulting focus event for the textfield
  2150. * (in onFocus).
  2151. */
  2152. preventNextBlurEventInIE = false;
  2153. Element focusedElement = WidgetUtil.getFocusedElement();
  2154. if (getElement().isOrHasChild(focusedElement) || suggestionPopup
  2155. .getElement().isOrHasChild(focusedElement)) {
  2156. // IF the suggestion popup or another part of the VFilterSelect
  2157. // was focused, move the focus back to the textfield and prevent
  2158. // the triggered focus event (in onFocus).
  2159. iePreventNextFocus = true;
  2160. tb.setFocus(true);
  2161. return;
  2162. }
  2163. }
  2164. focused = false;
  2165. if (!readonly) {
  2166. if (textInputEnabled && allowNewItem) {
  2167. suggestionPopup.menu.doSelectedItemAction();
  2168. }
  2169. if (selectedOptionKey == null) {
  2170. if (explicitSelectedCaption != null) {
  2171. setPromptingOff(explicitSelectedCaption);
  2172. } else {
  2173. setPromptingOn();
  2174. }
  2175. } else if (currentSuggestion != null) {
  2176. setPromptingOff(currentSuggestion.caption);
  2177. setSelectedItemIcon(currentSuggestion.getIconUri());
  2178. }
  2179. }
  2180. removeStyleDependentName("focus");
  2181. if (client.hasEventListeners(this, EventId.BLUR)) {
  2182. client.updateVariable(paintableId, EventId.BLUR, "", true);
  2183. afterUpdateClientVariables();
  2184. }
  2185. }
  2186. /*
  2187. * (non-Javadoc)
  2188. *
  2189. * @see com.vaadin.client.Focusable#focus()
  2190. */
  2191. @Override
  2192. public void focus() {
  2193. debug("VFS: focus()");
  2194. focused = true;
  2195. if (prompting && !readonly) {
  2196. setPromptingOff("");
  2197. }
  2198. tb.setFocus(true);
  2199. }
  2200. /**
  2201. * Calculates the width of the select if the select has undefined width.
  2202. * Should be called when the width changes or when the icon changes.
  2203. * <p>
  2204. * For internal use only. May be removed or replaced in the future.
  2205. */
  2206. public void updateRootWidth() {
  2207. ComponentConnector paintable = ConnectorMap.get(client)
  2208. .getConnector(this);
  2209. if (paintable.isUndefinedWidth()) {
  2210. /*
  2211. * When the select has a undefined with we need to check that we are
  2212. * only setting the text box width relative to the first page width
  2213. * of the items. If this is not done the text box width will change
  2214. * when the popup is used to view longer items than the text box is
  2215. * wide.
  2216. */
  2217. int w = WidgetUtil.getRequiredWidth(this);
  2218. if ((!initDone || currentPage + 1 < 0)
  2219. && suggestionPopupMinWidth > w) {
  2220. /*
  2221. * We want to compensate for the paddings just to preserve the
  2222. * exact size as in Vaadin 6.x, but we get here before
  2223. * MeasuredSize has been initialized.
  2224. * Util.measureHorizontalPaddingAndBorder does not work with
  2225. * border-box, so we must do this the hard way.
  2226. */
  2227. Style style = getElement().getStyle();
  2228. String originalPadding = style.getPadding();
  2229. String originalBorder = style.getBorderWidth();
  2230. style.setPaddingLeft(0, Unit.PX);
  2231. style.setBorderWidth(0, Unit.PX);
  2232. style.setProperty("padding", originalPadding);
  2233. style.setProperty("borderWidth", originalBorder);
  2234. // Use util.getRequiredWidth instead of getOffsetWidth here
  2235. int iconWidth = selectedItemIcon == null ? 0
  2236. : WidgetUtil.getRequiredWidth(selectedItemIcon);
  2237. int buttonWidth = popupOpener == null ? 0
  2238. : WidgetUtil.getRequiredWidth(popupOpener);
  2239. /*
  2240. * Instead of setting the width of the wrapper, set the width of
  2241. * the combobox. Subtract the width of the icon and the
  2242. * popupopener
  2243. */
  2244. tb.setWidth((suggestionPopupMinWidth - iconWidth - buttonWidth)
  2245. + "px");
  2246. }
  2247. /*
  2248. * Lock the textbox width to its current value if it's not already
  2249. * locked
  2250. */
  2251. if (!tb.getElement().getStyle().getWidth().endsWith("px")) {
  2252. int iconWidth = selectedItemIcon == null ? 0
  2253. : selectedItemIcon.getOffsetWidth();
  2254. tb.setWidth((tb.getOffsetWidth() - iconWidth) + "px");
  2255. }
  2256. }
  2257. }
  2258. /**
  2259. * Get the width of the select in pixels where the text area and icon has
  2260. * been included.
  2261. *
  2262. * @return The width in pixels
  2263. */
  2264. private int getMainWidth() {
  2265. return getOffsetWidth();
  2266. }
  2267. @Override
  2268. public void setWidth(String width) {
  2269. super.setWidth(width);
  2270. if (!width.isEmpty()) {
  2271. tb.setWidth("100%");
  2272. }
  2273. }
  2274. /**
  2275. * Handles special behavior of the mouse down event
  2276. *
  2277. * @param event
  2278. */
  2279. private void handleMouseDownEvent(Event event) {
  2280. /*
  2281. * Prevent the keyboard focus from leaving the textfield by preventing
  2282. * the default behavior of the browser. Fixes #4285.
  2283. */
  2284. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  2285. event.preventDefault();
  2286. event.stopPropagation();
  2287. /*
  2288. * In IE the above wont work, the blur event will still trigger. So,
  2289. * we set a flag here to prevent the next blur event from happening.
  2290. * This is not needed if do not already have focus, in that case
  2291. * there will not be any blur event and we should not cancel the
  2292. * next blur.
  2293. */
  2294. if (BrowserInfo.get().isIE() && focused) {
  2295. preventNextBlurEventInIE = true;
  2296. debug("VFS: Going to prevent next blur event on IE");
  2297. }
  2298. }
  2299. }
  2300. @Override
  2301. protected void onDetach() {
  2302. super.onDetach();
  2303. suggestionPopup.hide();
  2304. }
  2305. @Override
  2306. public com.google.gwt.user.client.Element getSubPartElement(
  2307. String subPart) {
  2308. String[] parts = subPart.split("/");
  2309. if ("textbox".equals(parts[0])) {
  2310. return tb.getElement();
  2311. } else if ("button".equals(parts[0])) {
  2312. return popupOpener.getElement();
  2313. } else if ("popup".equals(parts[0]) && suggestionPopup.isAttached()) {
  2314. if (parts.length == 2) {
  2315. return suggestionPopup.menu.getSubPartElement(parts[1]);
  2316. }
  2317. return suggestionPopup.getElement();
  2318. }
  2319. return null;
  2320. }
  2321. @Override
  2322. public String getSubPartName(
  2323. com.google.gwt.user.client.Element subElement) {
  2324. if (tb.getElement().isOrHasChild(subElement)) {
  2325. return "textbox";
  2326. } else if (popupOpener.getElement().isOrHasChild(subElement)) {
  2327. return "button";
  2328. } else if (suggestionPopup.getElement().isOrHasChild(subElement)) {
  2329. return "popup";
  2330. }
  2331. return null;
  2332. }
  2333. @Override
  2334. public void setAriaRequired(boolean required) {
  2335. AriaHelper.handleInputRequired(tb, required);
  2336. }
  2337. @Override
  2338. public void setAriaInvalid(boolean invalid) {
  2339. AriaHelper.handleInputInvalid(tb, invalid);
  2340. }
  2341. @Override
  2342. public void bindAriaCaption(
  2343. com.google.gwt.user.client.Element captionElement) {
  2344. AriaHelper.bindCaption(tb, captionElement);
  2345. }
  2346. /*
  2347. * Anything that should be set after the client updates the server.
  2348. */
  2349. private void afterUpdateClientVariables() {
  2350. // We need this here to be consistent with the all the calls.
  2351. // Then set your specific selection type only after
  2352. // client.updateVariable() method call.
  2353. selectPopupItemWhenResponseIsReceived = Select.NONE;
  2354. }
  2355. @Override
  2356. public boolean isWorkPending() {
  2357. return waitingForFilteringResponse
  2358. || suggestionPopup.lazyPageScroller.isRunning();
  2359. }
  2360. /**
  2361. * Sets the caption of selected item, if "scroll to page" is disabled. This
  2362. * method is meant for internal use and may change in future versions.
  2363. *
  2364. * @since 7.7
  2365. * @param selectedCaption
  2366. * the caption of selected item
  2367. */
  2368. public void setSelectedCaption(String selectedCaption) {
  2369. explicitSelectedCaption = selectedCaption;
  2370. if (selectedCaption != null) {
  2371. setPromptingOff(selectedCaption);
  2372. }
  2373. }
  2374. /**
  2375. * This method is meant for internal use and may change in future versions.
  2376. *
  2377. * @since 7.7
  2378. * @return the caption of selected item, if "scroll to page" is disabled
  2379. */
  2380. public String getSelectedCaption() {
  2381. return explicitSelectedCaption;
  2382. }
  2383. private static Logger getLogger() {
  2384. return Logger.getLogger(VFilterSelect.class.getName());
  2385. }
  2386. }