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

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