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.

VComboBox.java 104KB

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