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

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