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

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