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

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