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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client.ui;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.Date;
  8. import java.util.HashSet;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import java.util.Set;
  12. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  13. import com.google.gwt.dom.client.Style;
  14. import com.google.gwt.dom.client.Style.Unit;
  15. import com.google.gwt.event.dom.client.BlurEvent;
  16. import com.google.gwt.event.dom.client.BlurHandler;
  17. import com.google.gwt.event.dom.client.ClickEvent;
  18. import com.google.gwt.event.dom.client.ClickHandler;
  19. import com.google.gwt.event.dom.client.FocusEvent;
  20. import com.google.gwt.event.dom.client.FocusHandler;
  21. import com.google.gwt.event.dom.client.KeyCodes;
  22. import com.google.gwt.event.dom.client.KeyDownEvent;
  23. import com.google.gwt.event.dom.client.KeyDownHandler;
  24. import com.google.gwt.event.dom.client.KeyUpEvent;
  25. import com.google.gwt.event.dom.client.KeyUpHandler;
  26. import com.google.gwt.event.dom.client.LoadEvent;
  27. import com.google.gwt.event.dom.client.LoadHandler;
  28. import com.google.gwt.event.logical.shared.CloseEvent;
  29. import com.google.gwt.event.logical.shared.CloseHandler;
  30. import com.google.gwt.user.client.Command;
  31. import com.google.gwt.user.client.DOM;
  32. import com.google.gwt.user.client.Element;
  33. import com.google.gwt.user.client.Event;
  34. import com.google.gwt.user.client.Timer;
  35. import com.google.gwt.user.client.Window;
  36. import com.google.gwt.user.client.ui.Composite;
  37. import com.google.gwt.user.client.ui.FlowPanel;
  38. import com.google.gwt.user.client.ui.HTML;
  39. import com.google.gwt.user.client.ui.Image;
  40. import com.google.gwt.user.client.ui.PopupPanel;
  41. import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
  42. import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
  43. import com.google.gwt.user.client.ui.TextBox;
  44. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  45. import com.vaadin.terminal.gwt.client.BrowserInfo;
  46. import com.vaadin.terminal.gwt.client.ComponentState;
  47. import com.vaadin.terminal.gwt.client.EventId;
  48. import com.vaadin.terminal.gwt.client.Focusable;
  49. import com.vaadin.terminal.gwt.client.UIDL;
  50. import com.vaadin.terminal.gwt.client.Util;
  51. import com.vaadin.terminal.gwt.client.VConsole;
  52. import com.vaadin.terminal.gwt.client.ConnectorMap;
  53. import com.vaadin.terminal.gwt.client.ComponentConnector;
  54. import com.vaadin.terminal.gwt.client.VTooltip;
  55. /**
  56. * Client side implementation of the Select component.
  57. *
  58. * TODO needs major refactoring (to be extensible etc)
  59. */
  60. @SuppressWarnings("deprecation")
  61. public class VFilterSelect extends Composite implements Field, KeyDownHandler,
  62. KeyUpHandler, ClickHandler, FocusHandler, BlurHandler, Focusable {
  63. /**
  64. * Represents a suggestion in the suggestion popup box
  65. */
  66. public class FilterSelectSuggestion implements Suggestion, Command {
  67. private final String key;
  68. private final String caption;
  69. private String iconUri;
  70. /**
  71. * Constructor
  72. *
  73. * @param uidl
  74. * The UIDL recieved from the server
  75. */
  76. public FilterSelectSuggestion(UIDL uidl) {
  77. key = uidl.getStringAttribute("key");
  78. caption = uidl.getStringAttribute("caption");
  79. if (uidl.hasAttribute("icon")) {
  80. iconUri = client.translateVaadinUri(uidl
  81. .getStringAttribute("icon"));
  82. }
  83. }
  84. /**
  85. * Gets the visible row in the popup as a HTML string. The string
  86. * contains an image tag with the rows icon (if an icon has been
  87. * specified) and the caption of the item
  88. */
  89. public String getDisplayString() {
  90. final StringBuffer sb = new StringBuffer();
  91. if (iconUri != null) {
  92. sb.append("<img src=\"");
  93. sb.append(Util.escapeAttribute(iconUri));
  94. sb.append("\" alt=\"\" class=\"v-icon\" />");
  95. }
  96. String content;
  97. if ("".equals(caption)) {
  98. // Ensure that empty options use the same height as other
  99. // options and are not collapsed (#7506)
  100. content = "&nbsp;";
  101. } else {
  102. content = Util.escapeHTML(caption);
  103. }
  104. sb.append("<span>" + content + "</span>");
  105. return sb.toString();
  106. }
  107. /**
  108. * Get a string that represents this item. This is used in the text box.
  109. */
  110. public String getReplacementString() {
  111. return caption;
  112. }
  113. /**
  114. * Get the option key which represents the item on the server side.
  115. *
  116. * @return The key of the item
  117. */
  118. public int getOptionKey() {
  119. return Integer.parseInt(key);
  120. }
  121. /**
  122. * Get the URI of the icon. Used when constructing the displayed option.
  123. *
  124. * @return
  125. */
  126. public String getIconUri() {
  127. return iconUri;
  128. }
  129. /**
  130. * Executes a selection of this item.
  131. */
  132. public void execute() {
  133. onSuggestionSelected(this);
  134. }
  135. }
  136. /**
  137. * Represents the popup box with the selection options. Wraps a suggestion
  138. * menu.
  139. */
  140. public class SuggestionPopup extends VOverlay implements PositionCallback,
  141. CloseHandler<PopupPanel> {
  142. private static final String Z_INDEX = "30000";
  143. protected final SuggestionMenu menu;
  144. private final Element up = DOM.createDiv();
  145. private final Element down = DOM.createDiv();
  146. private final Element status = DOM.createDiv();
  147. private boolean isPagingEnabled = true;
  148. private long lastAutoClosed;
  149. private int popupOuterPadding = -1;
  150. private int topPosition;
  151. /**
  152. * Default constructor
  153. */
  154. SuggestionPopup() {
  155. super(true, false, true);
  156. menu = new SuggestionMenu();
  157. setWidget(menu);
  158. setStyleName(CLASSNAME + "-suggestpopup");
  159. DOM.setStyleAttribute(getElement(), "zIndex", Z_INDEX);
  160. final Element root = getContainerElement();
  161. DOM.setInnerHTML(up, "<span>Prev</span>");
  162. DOM.sinkEvents(up, Event.ONCLICK);
  163. DOM.setInnerHTML(down, "<span>Next</span>");
  164. DOM.sinkEvents(down, Event.ONCLICK);
  165. DOM.insertChild(root, up, 0);
  166. DOM.appendChild(root, down);
  167. DOM.appendChild(root, status);
  168. DOM.setElementProperty(status, "className", CLASSNAME + "-status");
  169. DOM.sinkEvents(root, Event.ONMOUSEDOWN | Event.ONMOUSEWHEEL);
  170. addCloseHandler(this);
  171. }
  172. /**
  173. * Shows the popup where the user can see the filtered options
  174. *
  175. * @param currentSuggestions
  176. * The filtered suggestions
  177. * @param currentPage
  178. * The current page number
  179. * @param totalSuggestions
  180. * The total amount of suggestions
  181. */
  182. public void showSuggestions(
  183. Collection<FilterSelectSuggestion> currentSuggestions,
  184. int currentPage, int totalSuggestions) {
  185. // Add TT anchor point
  186. DOM.setElementProperty(getElement(), "id",
  187. "VAADIN_COMBOBOX_OPTIONLIST");
  188. menu.setSuggestions(currentSuggestions);
  189. final int x = VFilterSelect.this.getAbsoluteLeft();
  190. topPosition = tb.getAbsoluteTop();
  191. topPosition += tb.getOffsetHeight();
  192. setPopupPosition(x, topPosition);
  193. int nullOffset = (nullSelectionAllowed && "".equals(lastFilter) ? 1
  194. : 0);
  195. boolean firstPage = (currentPage == 0);
  196. final int first = currentPage * pageLength + 1
  197. - (firstPage ? 0 : nullOffset);
  198. final int last = first + currentSuggestions.size() - 1
  199. - (firstPage && "".equals(lastFilter) ? nullOffset : 0);
  200. final int matches = totalSuggestions - nullOffset;
  201. if (last > 0) {
  202. // nullsel not counted, as requested by user
  203. DOM.setInnerText(status, (matches == 0 ? 0 : first) + "-"
  204. + last + "/" + matches);
  205. } else {
  206. DOM.setInnerText(status, "");
  207. }
  208. // We don't need to show arrows or statusbar if there is only one
  209. // page
  210. if (totalSuggestions <= pageLength || pageLength == 0) {
  211. setPagingEnabled(false);
  212. } else {
  213. setPagingEnabled(true);
  214. }
  215. setPrevButtonActive(first > 1);
  216. setNextButtonActive(last < matches);
  217. // clear previously fixed width
  218. menu.setWidth("");
  219. DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()),
  220. "width", "");
  221. setPopupPositionAndShow(this);
  222. }
  223. /**
  224. * Should the next page button be visible to the user?
  225. *
  226. * @param active
  227. */
  228. private void setNextButtonActive(boolean active) {
  229. if (active) {
  230. DOM.sinkEvents(down, Event.ONCLICK);
  231. DOM.setElementProperty(down, "className", CLASSNAME
  232. + "-nextpage");
  233. } else {
  234. DOM.sinkEvents(down, 0);
  235. DOM.setElementProperty(down, "className", CLASSNAME
  236. + "-nextpage-off");
  237. }
  238. }
  239. /**
  240. * Should the previous page button be visible to the user
  241. *
  242. * @param active
  243. */
  244. private void setPrevButtonActive(boolean active) {
  245. if (active) {
  246. DOM.sinkEvents(up, Event.ONCLICK);
  247. DOM.setElementProperty(up, "className", CLASSNAME + "-prevpage");
  248. } else {
  249. DOM.sinkEvents(up, 0);
  250. DOM.setElementProperty(up, "className", CLASSNAME
  251. + "-prevpage-off");
  252. }
  253. }
  254. /**
  255. * Selects the next item in the filtered selections
  256. */
  257. public void selectNextItem() {
  258. final MenuItem cur = menu.getSelectedItem();
  259. final int index = 1 + menu.getItems().indexOf(cur);
  260. if (menu.getItems().size() > index) {
  261. final MenuItem newSelectedItem = menu.getItems().get(index);
  262. menu.selectItem(newSelectedItem);
  263. tb.setText(newSelectedItem.getText());
  264. tb.setSelectionRange(lastFilter.length(), newSelectedItem
  265. .getText().length() - lastFilter.length());
  266. } else if (hasNextPage()) {
  267. selectPopupItemWhenResponseIsReceived = Select.FIRST;
  268. filterOptions(currentPage + 1, lastFilter);
  269. }
  270. }
  271. /**
  272. * Selects the previous item in the filtered selections
  273. */
  274. public void selectPrevItem() {
  275. final MenuItem cur = menu.getSelectedItem();
  276. final int index = -1 + menu.getItems().indexOf(cur);
  277. if (index > -1) {
  278. final MenuItem newSelectedItem = menu.getItems().get(index);
  279. menu.selectItem(newSelectedItem);
  280. tb.setText(newSelectedItem.getText());
  281. tb.setSelectionRange(lastFilter.length(), newSelectedItem
  282. .getText().length() - lastFilter.length());
  283. } else if (index == -1) {
  284. if (currentPage > 0) {
  285. selectPopupItemWhenResponseIsReceived = Select.LAST;
  286. filterOptions(currentPage - 1, lastFilter);
  287. }
  288. } else {
  289. final MenuItem newSelectedItem = menu.getItems().get(
  290. menu.getItems().size() - 1);
  291. menu.selectItem(newSelectedItem);
  292. tb.setText(newSelectedItem.getText());
  293. tb.setSelectionRange(lastFilter.length(), newSelectedItem
  294. .getText().length() - lastFilter.length());
  295. }
  296. }
  297. /*
  298. * Using a timer to scroll up or down the pages so when we receive lots
  299. * of consecutive mouse wheel events the pages does not flicker.
  300. */
  301. private LazyPageScroller lazyPageScroller = new LazyPageScroller();
  302. private class LazyPageScroller extends Timer {
  303. private int pagesToScroll = 0;
  304. @Override
  305. public void run() {
  306. if (pagesToScroll != 0) {
  307. if (!waitingForFilteringResponse) {
  308. /*
  309. * Avoid scrolling while we are waiting for a response
  310. * because otherwise the waiting flag will be reset in
  311. * the first response and the second response will be
  312. * ignored, causing an empty popup...
  313. *
  314. * As long as the scrolling delay is suitable
  315. * double/triple clicks will work by scrolling two or
  316. * three pages at a time and this should not be a
  317. * problem.
  318. */
  319. filterOptions(currentPage + pagesToScroll, lastFilter);
  320. }
  321. pagesToScroll = 0;
  322. }
  323. }
  324. public void scrollUp() {
  325. if (currentPage + pagesToScroll > 0) {
  326. pagesToScroll--;
  327. cancel();
  328. schedule(200);
  329. }
  330. }
  331. public void scrollDown() {
  332. if (totalMatches > (currentPage + pagesToScroll + 1)
  333. * pageLength) {
  334. pagesToScroll++;
  335. cancel();
  336. schedule(200);
  337. }
  338. }
  339. }
  340. /*
  341. * (non-Javadoc)
  342. *
  343. * @see
  344. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt
  345. * .user.client.Event)
  346. */
  347. @Override
  348. public void onBrowserEvent(Event event) {
  349. if (event.getTypeInt() == Event.ONCLICK) {
  350. final Element target = DOM.eventGetTarget(event);
  351. if (target == up || target == DOM.getChild(up, 0)) {
  352. lazyPageScroller.scrollUp();
  353. } else if (target == down || target == DOM.getChild(down, 0)) {
  354. lazyPageScroller.scrollDown();
  355. }
  356. } else if (event.getTypeInt() == Event.ONMOUSEWHEEL) {
  357. int velocity = event.getMouseWheelVelocityY();
  358. if (velocity > 0) {
  359. lazyPageScroller.scrollDown();
  360. } else {
  361. lazyPageScroller.scrollUp();
  362. }
  363. }
  364. /*
  365. * Prevent the keyboard focus from leaving the textfield by
  366. * preventing the default behaviour of the browser. Fixes #4285.
  367. */
  368. handleMouseDownEvent(event);
  369. }
  370. /**
  371. * Should paging be enabled. If paging is enabled then only a certain
  372. * amount of items are visible at a time and a scrollbar or buttons are
  373. * visible to change page. If paging is turned of then all options are
  374. * rendered into the popup menu.
  375. *
  376. * @param paging
  377. * Should the paging be turned on?
  378. */
  379. public void setPagingEnabled(boolean paging) {
  380. if (isPagingEnabled == paging) {
  381. return;
  382. }
  383. if (paging) {
  384. DOM.setStyleAttribute(down, "display", "");
  385. DOM.setStyleAttribute(up, "display", "");
  386. DOM.setStyleAttribute(status, "display", "");
  387. } else {
  388. DOM.setStyleAttribute(down, "display", "none");
  389. DOM.setStyleAttribute(up, "display", "none");
  390. DOM.setStyleAttribute(status, "display", "none");
  391. }
  392. isPagingEnabled = paging;
  393. }
  394. /*
  395. * (non-Javadoc)
  396. *
  397. * @see
  398. * com.google.gwt.user.client.ui.PopupPanel$PositionCallback#setPosition
  399. * (int, int)
  400. */
  401. public void setPosition(int offsetWidth, int offsetHeight) {
  402. int top = -1;
  403. int left = -1;
  404. // reset menu size and retrieve its "natural" size
  405. menu.setHeight("");
  406. if (currentPage > 0) {
  407. // fix height to avoid height change when getting to last page
  408. menu.fixHeightTo(pageLength);
  409. }
  410. offsetHeight = getOffsetHeight();
  411. final int desiredWidth = getMainWidth();
  412. int naturalMenuWidth = DOM.getElementPropertyInt(
  413. DOM.getFirstChild(menu.getElement()), "offsetWidth");
  414. if (popupOuterPadding == -1) {
  415. popupOuterPadding = Util.measureHorizontalPaddingAndBorder(
  416. getElement(), 2);
  417. }
  418. if (naturalMenuWidth < desiredWidth) {
  419. menu.setWidth((desiredWidth - popupOuterPadding) + "px");
  420. DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()),
  421. "width", "100%");
  422. naturalMenuWidth = desiredWidth;
  423. }
  424. if (BrowserInfo.get().isIE()) {
  425. /*
  426. * IE requires us to specify the width for the container
  427. * element. Otherwise it will be 100% wide
  428. */
  429. int rootWidth = naturalMenuWidth - popupOuterPadding;
  430. DOM.setStyleAttribute(getContainerElement(), "width", rootWidth
  431. + "px");
  432. }
  433. if (offsetHeight + getPopupTop() > Window.getClientHeight()
  434. + Window.getScrollTop()) {
  435. // popup on top of input instead
  436. top = getPopupTop() - offsetHeight
  437. - VFilterSelect.this.getOffsetHeight();
  438. if (top < 0) {
  439. top = 0;
  440. }
  441. } else {
  442. top = getPopupTop();
  443. /*
  444. * Take popup top margin into account. getPopupTop() returns the
  445. * top value including the margin but the value we give must not
  446. * include the margin.
  447. */
  448. int topMargin = (top - topPosition);
  449. top -= topMargin;
  450. }
  451. // fetch real width (mac FF bugs here due GWT popups overflow:auto )
  452. offsetWidth = DOM.getElementPropertyInt(
  453. DOM.getFirstChild(menu.getElement()), "offsetWidth");
  454. if (offsetWidth + getPopupLeft() > Window.getClientWidth()
  455. + Window.getScrollLeft()) {
  456. left = VFilterSelect.this.getAbsoluteLeft()
  457. + VFilterSelect.this.getOffsetWidth()
  458. + Window.getScrollLeft() - offsetWidth;
  459. if (left < 0) {
  460. left = 0;
  461. }
  462. } else {
  463. left = getPopupLeft();
  464. }
  465. setPopupPosition(left, top);
  466. }
  467. /**
  468. * Was the popup just closed?
  469. *
  470. * @return true if popup was just closed
  471. */
  472. public boolean isJustClosed() {
  473. final long now = (new Date()).getTime();
  474. return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200);
  475. }
  476. /*
  477. * (non-Javadoc)
  478. *
  479. * @see
  480. * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google
  481. * .gwt.event.logical.shared.CloseEvent)
  482. */
  483. @Override
  484. public void onClose(CloseEvent<PopupPanel> event) {
  485. if (event.isAutoClosed()) {
  486. lastAutoClosed = (new Date()).getTime();
  487. }
  488. }
  489. /**
  490. * Updates style names in suggestion popup to help theme building.
  491. *
  492. * @param uidl
  493. * UIDL for the whole combo box
  494. * @param componentState
  495. * shared state of the combo box
  496. */
  497. public void updateStyleNames(UIDL uidl, ComponentState componentState) {
  498. setStyleName(CLASSNAME + "-suggestpopup");
  499. final String[] styles = componentState.getStyle().split(" ");
  500. for (int i = 0; i < styles.length; i++) {
  501. if (!"".equals(styles[i])) {
  502. addStyleDependentName(styles[i]);
  503. }
  504. }
  505. }
  506. }
  507. /**
  508. * The menu where the suggestions are rendered
  509. */
  510. public class SuggestionMenu extends MenuBar implements SubPartAware,
  511. LoadHandler {
  512. /**
  513. * Tracks the item that is currently selected using the keyboard. This
  514. * is need only because mouseover changes the selection and we do not
  515. * want to use that selection when pressing enter to select the item.
  516. */
  517. private MenuItem keyboardSelectedItem;
  518. private VLazyExecutor delayedImageLoadExecutioner = new VLazyExecutor(
  519. 100, new ScheduledCommand() {
  520. public void execute() {
  521. if (suggestionPopup.isVisible()
  522. && suggestionPopup.isAttached()) {
  523. setWidth("");
  524. DOM.setStyleAttribute(
  525. DOM.getFirstChild(getElement()), "width",
  526. "");
  527. suggestionPopup
  528. .setPopupPositionAndShow(suggestionPopup);
  529. }
  530. }
  531. });
  532. /**
  533. * Default constructor
  534. */
  535. SuggestionMenu() {
  536. super(true);
  537. setStyleName(CLASSNAME + "-suggestmenu");
  538. addDomHandler(this, LoadEvent.getType());
  539. }
  540. /**
  541. * Fixes menus height to use same space as full page would use. Needed
  542. * to avoid height changes when quickly "scrolling" to last page
  543. */
  544. public void fixHeightTo(int pagelenth) {
  545. if (currentSuggestions.size() > 0) {
  546. final int pixels = pagelenth * (getOffsetHeight() - 2)
  547. / currentSuggestions.size();
  548. setHeight((pixels + 2) + "px");
  549. }
  550. }
  551. /**
  552. * Sets the suggestions rendered in the menu
  553. *
  554. * @param suggestions
  555. * The suggestions to be rendered in the menu
  556. */
  557. public void setSuggestions(
  558. Collection<FilterSelectSuggestion> suggestions) {
  559. // Reset keyboard selection when contents is updated to avoid
  560. // reusing old, invalid data
  561. setKeyboardSelectedItem(null);
  562. clearItems();
  563. final Iterator<FilterSelectSuggestion> it = suggestions.iterator();
  564. while (it.hasNext()) {
  565. final FilterSelectSuggestion s = it.next();
  566. final MenuItem mi = new MenuItem(s.getDisplayString(), true, s);
  567. Util.sinkOnloadForImages(mi.getElement());
  568. this.addItem(mi);
  569. if (s == currentSuggestion) {
  570. selectItem(mi);
  571. }
  572. }
  573. }
  574. /**
  575. * Send the current selection to the server. Triggered when a selection
  576. * is made or on a blur event.
  577. */
  578. public void doSelectedItemAction() {
  579. // do not send a value change event if null was and stays selected
  580. final String enteredItemValue = tb.getText();
  581. if (nullSelectionAllowed && "".equals(enteredItemValue)
  582. && selectedOptionKey != null
  583. && !"".equals(selectedOptionKey)) {
  584. if (nullSelectItem) {
  585. reset();
  586. return;
  587. }
  588. // null is not visible on pages != 0, and not visible when
  589. // filtering: handle separately
  590. client.updateVariable(paintableId, "filter", "", false);
  591. client.updateVariable(paintableId, "page", 0, false);
  592. client.updateVariable(paintableId, "selected", new String[] {},
  593. immediate);
  594. suggestionPopup.hide();
  595. return;
  596. }
  597. updateSelectionWhenReponseIsReceived = waitingForFilteringResponse;
  598. if (!waitingForFilteringResponse) {
  599. doPostFilterSelectedItemAction();
  600. }
  601. }
  602. /**
  603. * Triggered after a selection has been made
  604. */
  605. public void doPostFilterSelectedItemAction() {
  606. final MenuItem item = getSelectedItem();
  607. final String enteredItemValue = tb.getText();
  608. updateSelectionWhenReponseIsReceived = false;
  609. // check for exact match in menu
  610. int p = getItems().size();
  611. if (p > 0) {
  612. for (int i = 0; i < p; i++) {
  613. final MenuItem potentialExactMatch = getItems().get(i);
  614. if (potentialExactMatch.getText().equals(enteredItemValue)) {
  615. selectItem(potentialExactMatch);
  616. // do not send a value change event if null was and
  617. // stays selected
  618. if (!"".equals(enteredItemValue)
  619. || (selectedOptionKey != null && !""
  620. .equals(selectedOptionKey))) {
  621. doItemAction(potentialExactMatch, true);
  622. }
  623. suggestionPopup.hide();
  624. return;
  625. }
  626. }
  627. }
  628. if (allowNewItem) {
  629. if (!prompting && !enteredItemValue.equals(lastNewItemString)) {
  630. /*
  631. * Store last sent new item string to avoid double sends
  632. */
  633. lastNewItemString = enteredItemValue;
  634. client.updateVariable(paintableId, "newitem",
  635. enteredItemValue, immediate);
  636. }
  637. } else if (item != null
  638. && !"".equals(lastFilter)
  639. && (filteringmode == FILTERINGMODE_CONTAINS ? item
  640. .getText().toLowerCase()
  641. .contains(lastFilter.toLowerCase()) : item
  642. .getText().toLowerCase()
  643. .startsWith(lastFilter.toLowerCase()))) {
  644. doItemAction(item, true);
  645. } else {
  646. // currentSuggestion has key="" for nullselection
  647. if (currentSuggestion != null
  648. && !currentSuggestion.key.equals("")) {
  649. // An item (not null) selected
  650. String text = currentSuggestion.getReplacementString();
  651. tb.setText(text);
  652. selectedOptionKey = currentSuggestion.key;
  653. } else {
  654. // Null selected
  655. tb.setText("");
  656. selectedOptionKey = null;
  657. }
  658. }
  659. suggestionPopup.hide();
  660. }
  661. private static final String SUBPART_PREFIX = "item";
  662. public Element getSubPartElement(String subPart) {
  663. int index = Integer.parseInt(subPart.substring(SUBPART_PREFIX
  664. .length()));
  665. MenuItem item = getItems().get(index);
  666. return item.getElement();
  667. }
  668. public String getSubPartName(Element subElement) {
  669. if (!getElement().isOrHasChild(subElement)) {
  670. return null;
  671. }
  672. Element menuItemRoot = subElement;
  673. while (menuItemRoot != null
  674. && !menuItemRoot.getTagName().equalsIgnoreCase("td")) {
  675. menuItemRoot = menuItemRoot.getParentElement().cast();
  676. }
  677. // "menuItemRoot" is now the root of the menu item
  678. final int itemCount = getItems().size();
  679. for (int i = 0; i < itemCount; i++) {
  680. if (getItems().get(i).getElement() == menuItemRoot) {
  681. String name = SUBPART_PREFIX + i;
  682. return name;
  683. }
  684. }
  685. return null;
  686. }
  687. public void onLoad(LoadEvent event) {
  688. // Handle icon onload events to ensure shadow is resized
  689. // correctly
  690. delayedImageLoadExecutioner.trigger();
  691. }
  692. public void selectFirstItem() {
  693. MenuItem firstItem = getItems().get(0);
  694. selectItem(firstItem);
  695. }
  696. private MenuItem getKeyboardSelectedItem() {
  697. return keyboardSelectedItem;
  698. }
  699. protected void setKeyboardSelectedItem(MenuItem firstItem) {
  700. keyboardSelectedItem = firstItem;
  701. }
  702. public void selectLastItem() {
  703. List<MenuItem> items = getItems();
  704. MenuItem lastItem = items.get(items.size() - 1);
  705. selectItem(lastItem);
  706. }
  707. }
  708. public static final int FILTERINGMODE_OFF = 0;
  709. public static final int FILTERINGMODE_STARTSWITH = 1;
  710. public static final int FILTERINGMODE_CONTAINS = 2;
  711. private static final String CLASSNAME = "v-filterselect";
  712. private static final String STYLE_NO_INPUT = "no-input";
  713. protected int pageLength = 10;
  714. private boolean enableDebug = false;
  715. private final FlowPanel panel = new FlowPanel();
  716. /**
  717. * The text box where the filter is written
  718. */
  719. protected final TextBox tb = new TextBox() {
  720. /*
  721. * (non-Javadoc)
  722. *
  723. * @see
  724. * com.google.gwt.user.client.ui.TextBoxBase#onBrowserEvent(com.google
  725. * .gwt.user.client.Event)
  726. */
  727. @Override
  728. public void onBrowserEvent(Event event) {
  729. super.onBrowserEvent(event);
  730. if (client != null) {
  731. client.handleTooltipEvent(event, VFilterSelect.this);
  732. }
  733. }
  734. @Override
  735. // Overridden to avoid selecting text when text input is disabled
  736. public void setSelectionRange(int pos, int length) {
  737. if (textInputEnabled) {
  738. super.setSelectionRange(pos, length);
  739. } else {
  740. super.setSelectionRange(getValue().length(), 0);
  741. }
  742. };
  743. };
  744. protected final SuggestionPopup suggestionPopup = new SuggestionPopup();
  745. /**
  746. * Used when measuring the width of the popup
  747. */
  748. private final HTML popupOpener = new HTML("") {
  749. /*
  750. * (non-Javadoc)
  751. *
  752. * @see
  753. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt
  754. * .user.client.Event)
  755. */
  756. @Override
  757. public void onBrowserEvent(Event event) {
  758. super.onBrowserEvent(event);
  759. if (client != null) {
  760. client.handleTooltipEvent(event, VFilterSelect.this);
  761. }
  762. /*
  763. * Prevent the keyboard focus from leaving the textfield by
  764. * preventing the default behaviour of the browser. Fixes #4285.
  765. */
  766. handleMouseDownEvent(event);
  767. }
  768. };
  769. private final Image selectedItemIcon = new Image();
  770. protected ApplicationConnection client;
  771. protected String paintableId;
  772. protected int currentPage;
  773. /**
  774. * A collection of available suggestions (options) as received from the
  775. * server.
  776. */
  777. protected final List<FilterSelectSuggestion> currentSuggestions = new ArrayList<FilterSelectSuggestion>();
  778. protected boolean immediate;
  779. protected String selectedOptionKey;
  780. protected boolean waitingForFilteringResponse = false;
  781. protected boolean updateSelectionWhenReponseIsReceived = false;
  782. private boolean tabPressedWhenPopupOpen = false;
  783. protected boolean initDone = false;
  784. protected String lastFilter = "";
  785. protected enum Select {
  786. NONE, FIRST, LAST
  787. };
  788. protected Select selectPopupItemWhenResponseIsReceived = Select.NONE;
  789. /**
  790. * The current suggestion selected from the dropdown. This is one of the
  791. * values in currentSuggestions except when filtering, in this case
  792. * currentSuggestion might not be in currentSuggestions.
  793. */
  794. protected FilterSelectSuggestion currentSuggestion;
  795. protected int totalMatches;
  796. protected boolean allowNewItem;
  797. protected boolean nullSelectionAllowed;
  798. protected boolean nullSelectItem;
  799. protected boolean enabled;
  800. protected boolean readonly;
  801. protected int filteringmode = FILTERINGMODE_OFF;
  802. // shown in unfocused empty field, disappears on focus (e.g "Search here")
  803. private static final String CLASSNAME_PROMPT = "prompt";
  804. protected static final String ATTR_INPUTPROMPT = "prompt";
  805. public static final String ATTR_NO_TEXT_INPUT = "noInput";
  806. protected String inputPrompt = "";
  807. protected boolean prompting = false;
  808. // Set true when popupopened has been clicked. Cleared on each UIDL-update.
  809. // This handles the special case where are not filtering yet and the
  810. // selected value has changed on the server-side. See #2119
  811. protected boolean popupOpenerClicked;
  812. protected int suggestionPopupMinWidth = 0;
  813. private int popupWidth = -1;
  814. /*
  815. * Stores the last new item string to avoid double submissions. Cleared on
  816. * uidl updates
  817. */
  818. protected String lastNewItemString;
  819. protected boolean focused = false;
  820. /**
  821. * If set to false, the component should not allow entering text to the
  822. * field even for filtering.
  823. */
  824. private boolean textInputEnabled = true;
  825. /**
  826. * Default constructor
  827. */
  828. public VFilterSelect() {
  829. selectedItemIcon.setStyleName("v-icon");
  830. selectedItemIcon.addLoadHandler(new LoadHandler() {
  831. public void onLoad(LoadEvent event) {
  832. updateRootWidth();
  833. updateSelectedIconPosition();
  834. /*
  835. * Workaround for an IE bug where the text is positioned below
  836. * the icon (#3991)
  837. */
  838. if (BrowserInfo.get().isIE()) {
  839. Util.setStyleTemporarily(tb.getElement(), "paddingLeft",
  840. "0");
  841. }
  842. }
  843. });
  844. tb.sinkEvents(VTooltip.TOOLTIP_EVENTS);
  845. popupOpener.sinkEvents(VTooltip.TOOLTIP_EVENTS | Event.ONMOUSEDOWN);
  846. panel.add(tb);
  847. panel.add(popupOpener);
  848. initWidget(panel);
  849. setStyleName(CLASSNAME);
  850. tb.addKeyDownHandler(this);
  851. tb.addKeyUpHandler(this);
  852. tb.setStyleName(CLASSNAME + "-input");
  853. tb.addFocusHandler(this);
  854. tb.addBlurHandler(this);
  855. tb.addClickHandler(this);
  856. popupOpener.setStyleName(CLASSNAME + "-button");
  857. popupOpener.addClickHandler(this);
  858. }
  859. /**
  860. * Does the Select have more pages?
  861. *
  862. * @return true if a next page exists, else false if the current page is the
  863. * last page
  864. */
  865. public boolean hasNextPage() {
  866. if (totalMatches > (currentPage + 1) * pageLength) {
  867. return true;
  868. } else {
  869. return false;
  870. }
  871. }
  872. /**
  873. * Filters the options at a certain page. Uses the text box input as a
  874. * filter
  875. *
  876. * @param page
  877. * The page which items are to be filtered
  878. */
  879. public void filterOptions(int page) {
  880. filterOptions(page, tb.getText());
  881. }
  882. /**
  883. * Filters the options at certain page using the given filter
  884. *
  885. * @param page
  886. * The page to filter
  887. * @param filter
  888. * The filter to apply to the components
  889. */
  890. public void filterOptions(int page, String filter) {
  891. filterOptions(page, filter, true);
  892. }
  893. /**
  894. * Filters the options at certain page using the given filter
  895. *
  896. * @param page
  897. * The page to filter
  898. * @param filter
  899. * The filter to apply to the options
  900. * @param immediate
  901. * Whether to send the options request immediately
  902. */
  903. private void filterOptions(int page, String filter, boolean immediate) {
  904. if (filter.equals(lastFilter) && currentPage == page) {
  905. if (!suggestionPopup.isAttached()) {
  906. suggestionPopup.showSuggestions(currentSuggestions,
  907. currentPage, totalMatches);
  908. }
  909. return;
  910. }
  911. if (!filter.equals(lastFilter)) {
  912. // we are on subsequent page and text has changed -> reset page
  913. if ("".equals(filter)) {
  914. // let server decide
  915. page = -1;
  916. } else {
  917. page = 0;
  918. }
  919. }
  920. waitingForFilteringResponse = true;
  921. client.updateVariable(paintableId, "filter", filter, false);
  922. client.updateVariable(paintableId, "page", page, immediate);
  923. lastFilter = filter;
  924. currentPage = page;
  925. }
  926. protected void updateReadOnly() {
  927. tb.setReadOnly(readonly || !textInputEnabled);
  928. }
  929. protected void setTextInputEnabled(boolean textInputEnabled) {
  930. // Always update styles as they might have been overwritten
  931. if (textInputEnabled) {
  932. removeStyleDependentName(STYLE_NO_INPUT);
  933. } else {
  934. addStyleDependentName(STYLE_NO_INPUT);
  935. }
  936. if (this.textInputEnabled == textInputEnabled) {
  937. return;
  938. }
  939. this.textInputEnabled = textInputEnabled;
  940. updateReadOnly();
  941. }
  942. /**
  943. * Sets the text in the text box.
  944. *
  945. * @param text
  946. * the text to set in the text box
  947. */
  948. protected void setTextboxText(final String text) {
  949. tb.setText(text);
  950. }
  951. /**
  952. * Turns prompting on. When prompting is turned on a command prompt is shown
  953. * in the text box if nothing has been entered.
  954. */
  955. protected void setPromptingOn() {
  956. if (!prompting) {
  957. prompting = true;
  958. addStyleDependentName(CLASSNAME_PROMPT);
  959. }
  960. setTextboxText(inputPrompt);
  961. }
  962. /**
  963. * Turns prompting off. When prompting is turned on a command prompt is
  964. * shown in the text box if nothing has been entered.
  965. *
  966. * @param text
  967. * The text the text box should contain.
  968. */
  969. protected void setPromptingOff(String text) {
  970. setTextboxText(text);
  971. if (prompting) {
  972. prompting = false;
  973. removeStyleDependentName(CLASSNAME_PROMPT);
  974. }
  975. }
  976. /**
  977. * Triggered when a suggestion is selected
  978. *
  979. * @param suggestion
  980. * The suggestion that just got selected.
  981. */
  982. public void onSuggestionSelected(FilterSelectSuggestion suggestion) {
  983. updateSelectionWhenReponseIsReceived = false;
  984. currentSuggestion = suggestion;
  985. String newKey;
  986. if (suggestion.key.equals("")) {
  987. // "nullselection"
  988. newKey = "";
  989. } else {
  990. // normal selection
  991. newKey = String.valueOf(suggestion.getOptionKey());
  992. }
  993. String text = suggestion.getReplacementString();
  994. if ("".equals(newKey) && !focused) {
  995. setPromptingOn();
  996. } else {
  997. setPromptingOff(text);
  998. }
  999. setSelectedItemIcon(suggestion.getIconUri());
  1000. if (!(newKey.equals(selectedOptionKey) || ("".equals(newKey) && selectedOptionKey == null))) {
  1001. selectedOptionKey = newKey;
  1002. client.updateVariable(paintableId, "selected",
  1003. new String[] { selectedOptionKey }, immediate);
  1004. // currentPage = -1; // forget the page
  1005. }
  1006. suggestionPopup.hide();
  1007. }
  1008. /**
  1009. * Sets the icon URI of the selected item. The icon is shown on the left
  1010. * side of the item caption text. Set the URI to null to remove the icon.
  1011. *
  1012. * @param iconUri
  1013. * The URI of the icon
  1014. */
  1015. protected void setSelectedItemIcon(String iconUri) {
  1016. if (iconUri == null || iconUri.length() == 0) {
  1017. if (selectedItemIcon.isAttached()) {
  1018. panel.remove(selectedItemIcon);
  1019. updateRootWidth();
  1020. }
  1021. } else {
  1022. panel.insert(selectedItemIcon, 0);
  1023. selectedItemIcon.setUrl(iconUri);
  1024. updateRootWidth();
  1025. updateSelectedIconPosition();
  1026. }
  1027. }
  1028. /**
  1029. * Positions the icon vertically in the middle. Should be called after the
  1030. * icon has loaded
  1031. */
  1032. private void updateSelectedIconPosition() {
  1033. // Position icon vertically to middle
  1034. int availableHeight = 0;
  1035. availableHeight = getOffsetHeight();
  1036. int iconHeight = Util.getRequiredHeight(selectedItemIcon);
  1037. int marginTop = (availableHeight - iconHeight) / 2;
  1038. DOM.setStyleAttribute(selectedItemIcon.getElement(), "marginTop",
  1039. marginTop + "px");
  1040. }
  1041. private static Set<Integer> navigationKeyCodes = new HashSet<Integer>();
  1042. static {
  1043. navigationKeyCodes.add(KeyCodes.KEY_DOWN);
  1044. navigationKeyCodes.add(KeyCodes.KEY_UP);
  1045. navigationKeyCodes.add(KeyCodes.KEY_PAGEDOWN);
  1046. navigationKeyCodes.add(KeyCodes.KEY_PAGEUP);
  1047. navigationKeyCodes.add(KeyCodes.KEY_ENTER);
  1048. }
  1049. /*
  1050. * (non-Javadoc)
  1051. *
  1052. * @see
  1053. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1054. * .event.dom.client.KeyDownEvent)
  1055. */
  1056. public void onKeyDown(KeyDownEvent event) {
  1057. if (enabled && !readonly) {
  1058. int keyCode = event.getNativeKeyCode();
  1059. debug("key down: " + keyCode);
  1060. if (waitingForFilteringResponse
  1061. && navigationKeyCodes.contains(keyCode)) {
  1062. /*
  1063. * Keyboard navigation events should not be handled while we are
  1064. * waiting for a response. This avoids flickering, disappearing
  1065. * items, wrongly interpreted responses and more.
  1066. */
  1067. debug("Ignoring " + keyCode
  1068. + " because we are waiting for a filtering response");
  1069. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1070. event.stopPropagation();
  1071. return;
  1072. }
  1073. if (suggestionPopup.isAttached()) {
  1074. debug("Keycode " + keyCode + " target is popup");
  1075. popupKeyDown(event);
  1076. } else {
  1077. debug("Keycode " + keyCode + " target is text field");
  1078. inputFieldKeyDown(event);
  1079. }
  1080. }
  1081. }
  1082. private void debug(String string) {
  1083. if (enableDebug) {
  1084. VConsole.error(string);
  1085. }
  1086. }
  1087. /**
  1088. * Triggered when a key is pressed in the text box
  1089. *
  1090. * @param event
  1091. * The KeyDownEvent
  1092. */
  1093. private void inputFieldKeyDown(KeyDownEvent event) {
  1094. switch (event.getNativeKeyCode()) {
  1095. case KeyCodes.KEY_DOWN:
  1096. case KeyCodes.KEY_UP:
  1097. case KeyCodes.KEY_PAGEDOWN:
  1098. case KeyCodes.KEY_PAGEUP:
  1099. // open popup as from gadget
  1100. filterOptions(-1, "");
  1101. lastFilter = "";
  1102. tb.selectAll();
  1103. break;
  1104. case KeyCodes.KEY_ENTER:
  1105. /*
  1106. * This only handles the case when new items is allowed, a text is
  1107. * entered, the popup opener button is clicked to close the popup
  1108. * and enter is then pressed (see #7560).
  1109. */
  1110. if (!allowNewItem) {
  1111. return;
  1112. }
  1113. if (currentSuggestion != null
  1114. && tb.getText().equals(
  1115. currentSuggestion.getReplacementString())) {
  1116. // Retain behavior from #6686 by returning without stopping
  1117. // propagation if there's nothing to do
  1118. return;
  1119. }
  1120. suggestionPopup.menu.doSelectedItemAction();
  1121. event.stopPropagation();
  1122. break;
  1123. }
  1124. }
  1125. /**
  1126. * Triggered when a key was pressed in the suggestion popup.
  1127. *
  1128. * @param event
  1129. * The KeyDownEvent of the key
  1130. */
  1131. private void popupKeyDown(KeyDownEvent event) {
  1132. // Propagation of handled events is stopped so other handlers such as
  1133. // shortcut key handlers do not also handle the same events.
  1134. switch (event.getNativeKeyCode()) {
  1135. case KeyCodes.KEY_DOWN:
  1136. suggestionPopup.selectNextItem();
  1137. suggestionPopup.menu.setKeyboardSelectedItem(suggestionPopup.menu
  1138. .getSelectedItem());
  1139. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1140. event.stopPropagation();
  1141. break;
  1142. case KeyCodes.KEY_UP:
  1143. suggestionPopup.selectPrevItem();
  1144. suggestionPopup.menu.setKeyboardSelectedItem(suggestionPopup.menu
  1145. .getSelectedItem());
  1146. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1147. event.stopPropagation();
  1148. break;
  1149. case KeyCodes.KEY_PAGEDOWN:
  1150. if (hasNextPage()) {
  1151. filterOptions(currentPage + 1, lastFilter);
  1152. }
  1153. event.stopPropagation();
  1154. break;
  1155. case KeyCodes.KEY_PAGEUP:
  1156. if (currentPage > 0) {
  1157. filterOptions(currentPage - 1, lastFilter);
  1158. }
  1159. event.stopPropagation();
  1160. break;
  1161. case KeyCodes.KEY_TAB:
  1162. tabPressedWhenPopupOpen = true;
  1163. filterOptions(currentPage);
  1164. // onBlur() takes care of the rest
  1165. break;
  1166. case KeyCodes.KEY_ESCAPE:
  1167. reset();
  1168. event.stopPropagation();
  1169. break;
  1170. case KeyCodes.KEY_ENTER:
  1171. if (suggestionPopup.menu.getKeyboardSelectedItem() == null) {
  1172. /*
  1173. * Nothing selected using up/down. Happens e.g. when entering a
  1174. * text (causes popup to open) and then pressing enter.
  1175. */
  1176. if (!allowNewItem) {
  1177. /*
  1178. * New items are not allowed: If there is only one
  1179. * suggestion, select that. Otherwise do nothing.
  1180. */
  1181. if (currentSuggestions.size() == 1) {
  1182. onSuggestionSelected(currentSuggestions.get(0));
  1183. }
  1184. } else {
  1185. // Handle addition of new items.
  1186. suggestionPopup.menu.doSelectedItemAction();
  1187. }
  1188. } else {
  1189. /*
  1190. * Get the suggestion that was navigated to using up/down.
  1191. */
  1192. currentSuggestion = ((FilterSelectSuggestion) suggestionPopup.menu
  1193. .getKeyboardSelectedItem().getCommand());
  1194. onSuggestionSelected(currentSuggestion);
  1195. }
  1196. event.stopPropagation();
  1197. break;
  1198. }
  1199. }
  1200. /**
  1201. * Triggered when a key was depressed
  1202. *
  1203. * @param event
  1204. * The KeyUpEvent of the key depressed
  1205. */
  1206. public void onKeyUp(KeyUpEvent event) {
  1207. if (enabled && !readonly) {
  1208. switch (event.getNativeKeyCode()) {
  1209. case KeyCodes.KEY_ENTER:
  1210. case KeyCodes.KEY_TAB:
  1211. case KeyCodes.KEY_SHIFT:
  1212. case KeyCodes.KEY_CTRL:
  1213. case KeyCodes.KEY_ALT:
  1214. case KeyCodes.KEY_DOWN:
  1215. case KeyCodes.KEY_UP:
  1216. case KeyCodes.KEY_PAGEDOWN:
  1217. case KeyCodes.KEY_PAGEUP:
  1218. case KeyCodes.KEY_ESCAPE:
  1219. ; // NOP
  1220. break;
  1221. default:
  1222. if (textInputEnabled) {
  1223. filterOptions(currentPage);
  1224. }
  1225. break;
  1226. }
  1227. }
  1228. }
  1229. /**
  1230. * Resets the Select to its initial state
  1231. */
  1232. private void reset() {
  1233. if (currentSuggestion != null) {
  1234. String text = currentSuggestion.getReplacementString();
  1235. setPromptingOff(text);
  1236. selectedOptionKey = currentSuggestion.key;
  1237. } else {
  1238. if (focused) {
  1239. setPromptingOff("");
  1240. } else {
  1241. setPromptingOn();
  1242. }
  1243. selectedOptionKey = null;
  1244. }
  1245. lastFilter = "";
  1246. suggestionPopup.hide();
  1247. }
  1248. /**
  1249. * Listener for popupopener
  1250. */
  1251. public void onClick(ClickEvent event) {
  1252. if (textInputEnabled
  1253. && event.getNativeEvent().getEventTarget().cast() == tb
  1254. .getElement()) {
  1255. // Don't process clicks on the text field if text input is enabled
  1256. return;
  1257. }
  1258. if (enabled && !readonly) {
  1259. // ask suggestionPopup if it was just closed, we are using GWT
  1260. // Popup's auto close feature
  1261. if (!suggestionPopup.isJustClosed()) {
  1262. // If a focus event is not going to be sent, send the options
  1263. // request immediately; otherwise queue in the same burst as the
  1264. // focus event. Fixes #8321.
  1265. boolean immediate = focused
  1266. || !client.hasEventListeners(this, EventId.FOCUS);
  1267. filterOptions(-1, "", immediate);
  1268. popupOpenerClicked = true;
  1269. lastFilter = "";
  1270. }
  1271. DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
  1272. focus();
  1273. tb.selectAll();
  1274. }
  1275. }
  1276. /**
  1277. * Calculate minimum width for FilterSelect textarea
  1278. */
  1279. protected native int minWidth(String captions)
  1280. /*-{
  1281. if(!captions || captions.length <= 0)
  1282. return 0;
  1283. captions = captions.split("|");
  1284. var d = $wnd.document.createElement("div");
  1285. var html = "";
  1286. for(var i=0; i < captions.length; i++) {
  1287. html += "<div>" + captions[i] + "</div>";
  1288. // TODO apply same CSS classname as in suggestionmenu
  1289. }
  1290. d.style.position = "absolute";
  1291. d.style.top = "0";
  1292. d.style.left = "0";
  1293. d.style.visibility = "hidden";
  1294. d.innerHTML = html;
  1295. $wnd.document.body.appendChild(d);
  1296. var w = d.offsetWidth;
  1297. $wnd.document.body.removeChild(d);
  1298. return w;
  1299. }-*/;
  1300. /**
  1301. * A flag which prevents a focus event from taking place
  1302. */
  1303. boolean iePreventNextFocus = false;
  1304. /*
  1305. * (non-Javadoc)
  1306. *
  1307. * @see
  1308. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1309. * .dom.client.FocusEvent)
  1310. */
  1311. public void onFocus(FocusEvent event) {
  1312. /*
  1313. * When we disable a blur event in ie we need to refocus the textfield.
  1314. * This will cause a focus event we do not want to process, so in that
  1315. * case we just ignore it.
  1316. */
  1317. if (BrowserInfo.get().isIE() && iePreventNextFocus) {
  1318. iePreventNextFocus = false;
  1319. return;
  1320. }
  1321. focused = true;
  1322. if (prompting && !readonly) {
  1323. setPromptingOff("");
  1324. }
  1325. addStyleDependentName("focus");
  1326. if (client.hasEventListeners(this, EventId.FOCUS)) {
  1327. client.updateVariable(paintableId, EventId.FOCUS, "", true);
  1328. }
  1329. }
  1330. /**
  1331. * A flag which cancels the blur event and sets the focus back to the
  1332. * textfield if the Browser is IE
  1333. */
  1334. boolean preventNextBlurEventInIE = false;
  1335. /*
  1336. * (non-Javadoc)
  1337. *
  1338. * @see
  1339. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  1340. * .dom.client.BlurEvent)
  1341. */
  1342. public void onBlur(BlurEvent event) {
  1343. if (BrowserInfo.get().isIE() && preventNextBlurEventInIE) {
  1344. /*
  1345. * Clicking in the suggestion popup or on the popup button in IE
  1346. * causes a blur event to be sent for the field. In other browsers
  1347. * this is prevented by canceling/preventing default behavior for
  1348. * the focus event, in IE we handle it here by refocusing the text
  1349. * field and ignoring the resulting focus event for the textfield
  1350. * (in onFocus).
  1351. */
  1352. preventNextBlurEventInIE = false;
  1353. Element focusedElement = Util.getIEFocusedElement();
  1354. if (getElement().isOrHasChild(focusedElement)
  1355. || suggestionPopup.getElement()
  1356. .isOrHasChild(focusedElement)) {
  1357. // IF the suggestion popup or another part of the VFilterSelect
  1358. // was focused, move the focus back to the textfield and prevent
  1359. // the triggered focus event (in onFocus).
  1360. iePreventNextFocus = true;
  1361. tb.setFocus(true);
  1362. return;
  1363. }
  1364. }
  1365. focused = false;
  1366. if (!readonly) {
  1367. // much of the TAB handling takes place here
  1368. if (tabPressedWhenPopupOpen) {
  1369. tabPressedWhenPopupOpen = false;
  1370. suggestionPopup.menu.doSelectedItemAction();
  1371. suggestionPopup.hide();
  1372. } else if (!suggestionPopup.isAttached()
  1373. || suggestionPopup.isJustClosed()) {
  1374. suggestionPopup.menu.doSelectedItemAction();
  1375. }
  1376. if (selectedOptionKey == null) {
  1377. setPromptingOn();
  1378. } else if (currentSuggestion != null) {
  1379. setPromptingOff(currentSuggestion.caption);
  1380. }
  1381. }
  1382. removeStyleDependentName("focus");
  1383. if (client.hasEventListeners(this, EventId.BLUR)) {
  1384. client.updateVariable(paintableId, EventId.BLUR, "", true);
  1385. }
  1386. }
  1387. /*
  1388. * (non-Javadoc)
  1389. *
  1390. * @see com.vaadin.terminal.gwt.client.Focusable#focus()
  1391. */
  1392. public void focus() {
  1393. focused = true;
  1394. if (prompting && !readonly) {
  1395. setPromptingOff("");
  1396. }
  1397. tb.setFocus(true);
  1398. }
  1399. /**
  1400. * Calculates the width of the select if the select has undefined width.
  1401. * Should be called when the width changes or when the icon changes.
  1402. */
  1403. protected void updateRootWidth() {
  1404. ComponentConnector paintable = ConnectorMap.get(client).getConnector(
  1405. this);
  1406. if (paintable.isUndefinedWidth()) {
  1407. /*
  1408. * When the select has a undefined with we need to check that we are
  1409. * only setting the text box width relative to the first page width
  1410. * of the items. If this is not done the text box width will change
  1411. * when the popup is used to view longer items than the text box is
  1412. * wide.
  1413. */
  1414. int w = Util.getRequiredWidth(this);
  1415. if ((!initDone || currentPage + 1 < 0)
  1416. && suggestionPopupMinWidth > w) {
  1417. /*
  1418. * We want to compensate for the paddings just to preserve the
  1419. * exact size as in Vaadin 6.x, but we get here before
  1420. * MeasuredSize has been initialized.
  1421. * Util.measureHorizontalPaddingAndBorder does not work with
  1422. * border-box, so we must do this the hard way.
  1423. */
  1424. Style style = getElement().getStyle();
  1425. String originalPadding = style.getPadding();
  1426. String originalBorder = style.getBorderWidth();
  1427. style.setPaddingLeft(0, Unit.PX);
  1428. style.setBorderWidth(0, Unit.PX);
  1429. int offset = w - Util.getRequiredWidth(this);
  1430. style.setProperty("padding", originalPadding);
  1431. style.setProperty("borderWidth", originalBorder);
  1432. setWidth(suggestionPopupMinWidth + offset + "px");
  1433. }
  1434. /*
  1435. * Lock the textbox width to its current value if it's not already
  1436. * locked
  1437. */
  1438. if (!tb.getElement().getStyle().getWidth().endsWith("px")) {
  1439. tb.setWidth((tb.getOffsetWidth() - selectedItemIcon
  1440. .getOffsetWidth()) + "px");
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * Get the width of the select in pixels where the text area and icon has
  1446. * been included.
  1447. *
  1448. * @return The width in pixels
  1449. */
  1450. private int getMainWidth() {
  1451. return getOffsetWidth();
  1452. }
  1453. @Override
  1454. public void setWidth(String width) {
  1455. super.setWidth(width);
  1456. if (width.length() != 0) {
  1457. tb.setWidth("100%");
  1458. }
  1459. }
  1460. /**
  1461. * Handles special behavior of the mouse down event
  1462. *
  1463. * @param event
  1464. */
  1465. private void handleMouseDownEvent(Event event) {
  1466. /*
  1467. * Prevent the keyboard focus from leaving the textfield by preventing
  1468. * the default behaviour of the browser. Fixes #4285.
  1469. */
  1470. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  1471. event.preventDefault();
  1472. event.stopPropagation();
  1473. /*
  1474. * In IE the above wont work, the blur event will still trigger. So,
  1475. * we set a flag here to prevent the next blur event from happening.
  1476. * This is not needed if do not already have focus, in that case
  1477. * there will not be any blur event and we should not cancel the
  1478. * next blur.
  1479. */
  1480. if (BrowserInfo.get().isIE() && focused) {
  1481. preventNextBlurEventInIE = true;
  1482. }
  1483. }
  1484. }
  1485. @Override
  1486. protected void onDetach() {
  1487. super.onDetach();
  1488. suggestionPopup.hide();
  1489. }
  1490. }