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

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