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

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