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

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