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

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