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.

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