Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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