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

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