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

VFilterSelect.java 89KB

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