You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VTabsheet.java 59KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  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.Iterator;
  18. import java.util.List;
  19. import com.google.gwt.aria.client.Id;
  20. import com.google.gwt.aria.client.LiveValue;
  21. import com.google.gwt.aria.client.Roles;
  22. import com.google.gwt.aria.client.SelectedValue;
  23. import com.google.gwt.core.client.Scheduler;
  24. import com.google.gwt.dom.client.DivElement;
  25. import com.google.gwt.dom.client.Element;
  26. import com.google.gwt.dom.client.Style;
  27. import com.google.gwt.dom.client.Style.Display;
  28. import com.google.gwt.dom.client.Style.Overflow;
  29. import com.google.gwt.dom.client.Style.Unit;
  30. import com.google.gwt.dom.client.Style.Visibility;
  31. import com.google.gwt.dom.client.TableCellElement;
  32. import com.google.gwt.dom.client.TableElement;
  33. import com.google.gwt.event.dom.client.BlurEvent;
  34. import com.google.gwt.event.dom.client.BlurHandler;
  35. import com.google.gwt.event.dom.client.ClickEvent;
  36. import com.google.gwt.event.dom.client.ClickHandler;
  37. import com.google.gwt.event.dom.client.FocusEvent;
  38. import com.google.gwt.event.dom.client.FocusHandler;
  39. import com.google.gwt.event.dom.client.HasBlurHandlers;
  40. import com.google.gwt.event.dom.client.HasFocusHandlers;
  41. import com.google.gwt.event.dom.client.HasKeyDownHandlers;
  42. import com.google.gwt.event.dom.client.HasMouseDownHandlers;
  43. import com.google.gwt.event.dom.client.KeyCodes;
  44. import com.google.gwt.event.dom.client.KeyDownEvent;
  45. import com.google.gwt.event.dom.client.KeyDownHandler;
  46. import com.google.gwt.event.dom.client.MouseDownEvent;
  47. import com.google.gwt.event.dom.client.MouseDownHandler;
  48. import com.google.gwt.event.shared.HandlerRegistration;
  49. import com.google.gwt.regexp.shared.MatchResult;
  50. import com.google.gwt.regexp.shared.RegExp;
  51. import com.google.gwt.user.client.Command;
  52. import com.google.gwt.user.client.DOM;
  53. import com.google.gwt.user.client.Event;
  54. import com.google.gwt.user.client.ui.ComplexPanel;
  55. import com.google.gwt.user.client.ui.SimplePanel;
  56. import com.google.gwt.user.client.ui.Widget;
  57. import com.google.gwt.user.client.ui.impl.FocusImpl;
  58. import com.vaadin.client.ApplicationConnection;
  59. import com.vaadin.client.BrowserInfo;
  60. import com.vaadin.client.ComponentConnector;
  61. import com.vaadin.client.Focusable;
  62. import com.vaadin.client.TooltipInfo;
  63. import com.vaadin.client.Util;
  64. import com.vaadin.client.VCaption;
  65. import com.vaadin.client.VTooltip;
  66. import com.vaadin.client.ui.aria.AriaHelper;
  67. import com.vaadin.shared.AbstractComponentState;
  68. import com.vaadin.shared.ComponentConstants;
  69. import com.vaadin.shared.EventId;
  70. import com.vaadin.shared.communication.FieldRpc.FocusAndBlurServerRpc;
  71. import com.vaadin.shared.ui.ComponentStateUtil;
  72. import com.vaadin.shared.ui.tabsheet.TabState;
  73. import com.vaadin.shared.ui.tabsheet.TabsheetServerRpc;
  74. import com.vaadin.shared.ui.tabsheet.TabsheetState;
  75. public class VTabsheet extends VTabsheetBase implements Focusable, SubPartAware {
  76. private static class VCloseEvent {
  77. private Tab tab;
  78. VCloseEvent(Tab tab) {
  79. this.tab = tab;
  80. }
  81. public Tab getTab() {
  82. return tab;
  83. }
  84. }
  85. private interface VCloseHandler {
  86. public void onClose(VCloseEvent event);
  87. }
  88. /**
  89. * Representation of a single "tab" shown in the TabBar
  90. *
  91. */
  92. public static class Tab extends SimplePanel implements HasFocusHandlers,
  93. HasBlurHandlers, HasMouseDownHandlers, HasKeyDownHandlers {
  94. private static final String TD_CLASSNAME = CLASSNAME + "-tabitemcell";
  95. private static final String TD_FIRST_CLASSNAME = TD_CLASSNAME
  96. + "-first";
  97. private static final String TD_SELECTED_CLASSNAME = TD_CLASSNAME
  98. + "-selected";
  99. private static final String TD_SELECTED_FIRST_CLASSNAME = TD_SELECTED_CLASSNAME
  100. + "-first";
  101. private static final String TD_FOCUS_CLASSNAME = TD_CLASSNAME
  102. + "-focus";
  103. private static final String TD_FOCUS_FIRST_CLASSNAME = TD_FOCUS_CLASSNAME
  104. + "-first";
  105. private static final String TD_DISABLED_CLASSNAME = TD_CLASSNAME
  106. + "-disabled";
  107. private static final String DIV_CLASSNAME = CLASSNAME + "-tabitem";
  108. private static final String DIV_SELECTED_CLASSNAME = DIV_CLASSNAME
  109. + "-selected";
  110. private static final String DIV_FOCUS_CLASSNAME = DIV_CLASSNAME
  111. + "-focus";
  112. private TabCaption tabCaption;
  113. Element td = getElement();
  114. private VCloseHandler closeHandler;
  115. private boolean enabledOnServer = true;
  116. private Element div;
  117. private TabBar tabBar;
  118. private boolean hiddenOnServer = false;
  119. private String styleName;
  120. private String id;
  121. private Tab(TabBar tabBar) {
  122. super(DOM.createTD());
  123. this.tabBar = tabBar;
  124. setStyleName(td, TD_CLASSNAME);
  125. Roles.getTabRole().set(getElement());
  126. Roles.getTabRole().setAriaSelectedState(getElement(),
  127. SelectedValue.FALSE);
  128. div = DOM.createDiv();
  129. setTabulatorIndex(-1);
  130. setStyleName(div, DIV_CLASSNAME);
  131. DOM.appendChild(td, div);
  132. tabCaption = new TabCaption(this);
  133. add(tabCaption);
  134. Roles.getTabRole().setAriaLabelledbyProperty(getElement(),
  135. Id.of(tabCaption.getElement()));
  136. }
  137. public boolean isHiddenOnServer() {
  138. return hiddenOnServer;
  139. }
  140. public void setHiddenOnServer(boolean hiddenOnServer) {
  141. this.hiddenOnServer = hiddenOnServer;
  142. Roles.getTabRole().setAriaHiddenState(getElement(), hiddenOnServer);
  143. }
  144. @Override
  145. protected com.google.gwt.user.client.Element getContainerElement() {
  146. // Attach caption element to div, not td
  147. return DOM.asOld(div);
  148. }
  149. public boolean isEnabledOnServer() {
  150. return enabledOnServer;
  151. }
  152. public void setEnabledOnServer(boolean enabled) {
  153. enabledOnServer = enabled;
  154. Roles.getTabRole().setAriaDisabledState(getElement(), !enabled);
  155. setStyleName(td, TD_DISABLED_CLASSNAME, !enabled);
  156. if (!enabled) {
  157. focusImpl.setTabIndex(td, -1);
  158. }
  159. }
  160. public void addClickHandler(ClickHandler handler) {
  161. tabCaption.addClickHandler(handler);
  162. }
  163. public void setCloseHandler(VCloseHandler closeHandler) {
  164. this.closeHandler = closeHandler;
  165. }
  166. /**
  167. * Toggles the style names for the Tab
  168. *
  169. * @param selected
  170. * true if the Tab is selected
  171. * @param first
  172. * true if the Tab is the first visible Tab
  173. */
  174. public void setStyleNames(boolean selected, boolean first) {
  175. setStyleNames(selected, first, false);
  176. }
  177. public void setStyleNames(boolean selected, boolean first,
  178. boolean keyboardFocus) {
  179. setStyleName(td, TD_FIRST_CLASSNAME, first);
  180. setStyleName(td, TD_SELECTED_CLASSNAME, selected);
  181. setStyleName(td, TD_SELECTED_FIRST_CLASSNAME, selected && first);
  182. setStyleName(div, DIV_SELECTED_CLASSNAME, selected);
  183. setStyleName(td, TD_FOCUS_CLASSNAME, keyboardFocus);
  184. setStyleName(td, TD_FOCUS_FIRST_CLASSNAME, keyboardFocus && first);
  185. setStyleName(div, DIV_FOCUS_CLASSNAME, keyboardFocus);
  186. }
  187. public void setTabulatorIndex(int tabIndex) {
  188. getElement().setTabIndex(tabIndex);
  189. }
  190. public boolean isClosable() {
  191. return tabCaption.isClosable();
  192. }
  193. public void onClose() {
  194. closeHandler.onClose(new VCloseEvent(this));
  195. }
  196. public VTabsheet getTabsheet() {
  197. return tabBar.getTabsheet();
  198. }
  199. private void updateFromState(TabState tabState) {
  200. tabCaption.update(tabState);
  201. // Apply the styleName set for the tab
  202. String newStyleName = tabState.styleName;
  203. // Find the nth td element
  204. if (newStyleName != null && !newStyleName.isEmpty()) {
  205. if (!newStyleName.equals(styleName)) {
  206. // If we have a new style name
  207. if (styleName != null && !styleName.isEmpty()) {
  208. // Remove old style name if present
  209. td.removeClassName(TD_CLASSNAME + "-" + styleName);
  210. }
  211. // Set new style name
  212. td.addClassName(TD_CLASSNAME + "-" + newStyleName);
  213. styleName = newStyleName;
  214. }
  215. } else if (styleName != null) {
  216. // Remove the set stylename if no stylename is present in the
  217. // uidl
  218. td.removeClassName(TD_CLASSNAME + "-" + styleName);
  219. styleName = null;
  220. }
  221. String newId = tabState.id;
  222. if (newId != null && !newId.isEmpty()) {
  223. td.setId(newId);
  224. id = newId;
  225. } else if (id != null) {
  226. td.removeAttribute("id");
  227. id = null;
  228. }
  229. }
  230. public void recalculateCaptionWidth() {
  231. tabCaption.setWidth(tabCaption.getRequiredWidth() + "px");
  232. }
  233. @Override
  234. public HandlerRegistration addFocusHandler(FocusHandler handler) {
  235. return addDomHandler(handler, FocusEvent.getType());
  236. }
  237. @Override
  238. public HandlerRegistration addBlurHandler(BlurHandler handler) {
  239. return addDomHandler(handler, BlurEvent.getType());
  240. }
  241. @Override
  242. public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) {
  243. return addDomHandler(handler, MouseDownEvent.getType());
  244. }
  245. @Override
  246. public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) {
  247. return addDomHandler(handler, KeyDownEvent.getType());
  248. }
  249. public void focus() {
  250. getTabsheet().scrollIntoView(this);
  251. focusImpl.focus(td);
  252. }
  253. public void blur() {
  254. focusImpl.blur(td);
  255. }
  256. public boolean hasTooltip() {
  257. return tabCaption.getTooltipInfo() != null;
  258. }
  259. public TooltipInfo getTooltipInfo() {
  260. return tabCaption.getTooltipInfo();
  261. }
  262. public void setAssistiveDescription(String descriptionId) {
  263. Roles.getTablistRole().setAriaDescribedbyProperty(getElement(),
  264. Id.of(descriptionId));
  265. }
  266. public void removeAssistiveDescription() {
  267. Roles.getTablistRole().removeAriaDescribedbyProperty(getElement());
  268. }
  269. }
  270. public static class TabCaption extends VCaption {
  271. private boolean closable = false;
  272. private Element closeButton;
  273. private Tab tab;
  274. TabCaption(Tab tab) {
  275. super(tab.getTabsheet().connector.getConnection());
  276. this.tab = tab;
  277. AriaHelper.ensureHasId(getElement());
  278. }
  279. private boolean update(TabState tabState) {
  280. if (tabState.description != null || tabState.componentError != null) {
  281. setTooltipInfo(new TooltipInfo(tabState.description,
  282. tabState.componentError, this));
  283. } else {
  284. setTooltipInfo(null);
  285. }
  286. // TODO need to call this instead of super because the caption does
  287. // not have an owner
  288. String captionString = tabState.caption.isEmpty() ? null
  289. : tabState.caption;
  290. boolean ret = updateCaptionWithoutOwner(captionString,
  291. !tabState.enabled, hasAttribute(tabState.description),
  292. hasAttribute(tabState.componentError),
  293. tab.getTabsheet().connector
  294. .getResourceUrl(ComponentConstants.ICON_RESOURCE
  295. + tabState.key), tabState.iconAltText);
  296. setClosable(tabState.closable);
  297. return ret;
  298. }
  299. private boolean hasAttribute(String string) {
  300. return string != null && !string.trim().isEmpty();
  301. }
  302. private VTabsheet getTabsheet() {
  303. return tab.getTabsheet();
  304. }
  305. @Override
  306. public void onBrowserEvent(Event event) {
  307. if (closable && event.getTypeInt() == Event.ONCLICK
  308. && event.getEventTarget().cast() == closeButton) {
  309. tab.onClose();
  310. event.stopPropagation();
  311. event.preventDefault();
  312. }
  313. super.onBrowserEvent(event);
  314. if (event.getTypeInt() == Event.ONLOAD) {
  315. getTabsheet().tabSizeMightHaveChanged(getTab());
  316. }
  317. }
  318. public Tab getTab() {
  319. return tab;
  320. }
  321. public void setClosable(boolean closable) {
  322. this.closable = closable;
  323. if (closable && closeButton == null) {
  324. closeButton = DOM.createSpan();
  325. closeButton.setInnerHTML("×");
  326. closeButton
  327. .setClassName(VTabsheet.CLASSNAME + "-caption-close");
  328. Roles.getTabRole().setAriaHiddenState(closeButton, true);
  329. Roles.getTabRole().setAriaDisabledState(closeButton, true);
  330. getElement().appendChild(closeButton);
  331. } else if (!closable && closeButton != null) {
  332. getElement().removeChild(closeButton);
  333. closeButton = null;
  334. }
  335. if (closable) {
  336. addStyleDependentName("closable");
  337. } else {
  338. removeStyleDependentName("closable");
  339. }
  340. }
  341. public boolean isClosable() {
  342. return closable;
  343. }
  344. @Override
  345. public int getRequiredWidth() {
  346. int width = super.getRequiredWidth();
  347. if (closeButton != null) {
  348. width += Util.getRequiredWidth(closeButton);
  349. }
  350. return width;
  351. }
  352. public com.google.gwt.user.client.Element getCloseButton() {
  353. return DOM.asOld(closeButton);
  354. }
  355. }
  356. static class TabBar extends ComplexPanel implements VCloseHandler {
  357. private final Element tr = DOM.createTR();
  358. private final Element spacerTd = DOM.createTD();
  359. private Tab selected;
  360. private VTabsheet tabsheet;
  361. TabBar(VTabsheet tabsheet) {
  362. this.tabsheet = tabsheet;
  363. Element el = DOM.createTable();
  364. Roles.getPresentationRole().set(el);
  365. Element tbody = DOM.createTBody();
  366. DOM.appendChild(el, tbody);
  367. DOM.appendChild(tbody, tr);
  368. setStyleName(spacerTd, CLASSNAME + "-spacertd");
  369. DOM.appendChild(tr, spacerTd);
  370. DOM.appendChild(spacerTd, DOM.createDiv());
  371. setElement(el);
  372. }
  373. @Override
  374. public void onClose(VCloseEvent event) {
  375. Tab tab = event.getTab();
  376. if (!tab.isEnabledOnServer()) {
  377. return;
  378. }
  379. int tabIndex = getWidgetIndex(tab);
  380. getTabsheet().sendTabClosedEvent(tabIndex);
  381. }
  382. protected com.google.gwt.user.client.Element getContainerElement() {
  383. return DOM.asOld(tr);
  384. }
  385. /**
  386. * Gets the number of tabs from the tab bar.
  387. *
  388. * @return the number of tabs from the tab bar.
  389. */
  390. public int getTabCount() {
  391. return getWidgetCount();
  392. }
  393. /**
  394. * Adds a tab to the tab bar.
  395. *
  396. * @return the added tab.
  397. */
  398. public Tab addTab() {
  399. Tab t = new Tab(this);
  400. int tabIndex = getTabCount();
  401. // Logical attach
  402. insert(t, tr, tabIndex, true);
  403. if (tabIndex == 0) {
  404. // Set the "first" style
  405. t.setStyleNames(false, true);
  406. }
  407. getTabsheet().selectionHandler.registerTab(t);
  408. t.setCloseHandler(this);
  409. return t;
  410. }
  411. /**
  412. * Gets the tab sheet instance where the tab bar is attached to.
  413. *
  414. * @return the tab sheet instance where the tab bar is attached to.
  415. */
  416. public VTabsheet getTabsheet() {
  417. return tabsheet;
  418. }
  419. public Tab getTab(int index) {
  420. if (index < 0 || index >= getTabCount()) {
  421. return null;
  422. }
  423. return (Tab) super.getWidget(index);
  424. }
  425. public void selectTab(int index) {
  426. final Tab newSelected = getTab(index);
  427. final Tab oldSelected = selected;
  428. newSelected.setStyleNames(true, isFirstVisibleTab(index), true);
  429. newSelected.setTabulatorIndex(getTabsheet().tabulatorIndex);
  430. Roles.getTabRole().setAriaSelectedState(newSelected.getElement(),
  431. SelectedValue.TRUE);
  432. if (oldSelected != null && oldSelected != newSelected) {
  433. oldSelected.setStyleNames(false,
  434. isFirstVisibleTab(getWidgetIndex(oldSelected)));
  435. oldSelected.setTabulatorIndex(-1);
  436. Roles.getTabRole().setAriaSelectedState(
  437. oldSelected.getElement(), SelectedValue.FALSE);
  438. }
  439. // Update the field holding the currently selected tab
  440. selected = newSelected;
  441. // The selected tab might need more (or less) space
  442. newSelected.recalculateCaptionWidth();
  443. getTab(tabsheet.activeTabIndex).recalculateCaptionWidth();
  444. }
  445. public Tab navigateTab(int fromIndex, int toIndex) {
  446. Tab newNavigated = getTab(toIndex);
  447. if (newNavigated == null) {
  448. throw new IllegalArgumentException(
  449. "Tab at provided index toIndex was not found");
  450. }
  451. Tab oldNavigated = getTab(fromIndex);
  452. newNavigated.setStyleNames(newNavigated.equals(selected),
  453. isFirstVisibleTab(toIndex), true);
  454. if (oldNavigated != null && fromIndex != toIndex) {
  455. oldNavigated.setStyleNames(oldNavigated.equals(selected),
  456. isFirstVisibleTab(fromIndex), false);
  457. }
  458. return newNavigated;
  459. }
  460. public void removeTab(int i) {
  461. Tab tab = getTab(i);
  462. if (tab == null) {
  463. return;
  464. }
  465. remove(tab);
  466. /*
  467. * If this widget was selected we need to unmark it as the last
  468. * selected
  469. */
  470. if (tab == selected) {
  471. selected = null;
  472. }
  473. // FIXME: Shouldn't something be selected instead?
  474. }
  475. private boolean isFirstVisibleTab(int index) {
  476. return getFirstVisibleTab() == index;
  477. }
  478. /**
  479. * Returns the index of the first visible tab
  480. *
  481. * @return
  482. */
  483. private int getFirstVisibleTab() {
  484. return getNextVisibleTab(-1);
  485. }
  486. /**
  487. * Find the next visible tab. Returns -1 if none is found.
  488. *
  489. * @param i
  490. * @return
  491. */
  492. private int getNextVisibleTab(int i) {
  493. int tabs = getTabCount();
  494. do {
  495. i++;
  496. } while (i < tabs && getTab(i).isHiddenOnServer());
  497. if (i == tabs) {
  498. return -1;
  499. } else {
  500. return i;
  501. }
  502. }
  503. /**
  504. * Find the previous visible tab. Returns -1 if none is found.
  505. *
  506. * @param i
  507. * @return
  508. */
  509. private int getPreviousVisibleTab(int i) {
  510. do {
  511. i--;
  512. } while (i >= 0 && getTab(i).isHiddenOnServer());
  513. return i;
  514. }
  515. public int scrollLeft(int currentFirstVisible) {
  516. int prevVisible = getPreviousVisibleTab(currentFirstVisible);
  517. if (prevVisible == -1) {
  518. return -1;
  519. }
  520. Tab newFirst = getTab(prevVisible);
  521. newFirst.setVisible(true);
  522. newFirst.recalculateCaptionWidth();
  523. return prevVisible;
  524. }
  525. public int scrollRight(int currentFirstVisible) {
  526. int nextVisible = getNextVisibleTab(currentFirstVisible);
  527. if (nextVisible == -1) {
  528. return -1;
  529. }
  530. Tab currentFirst = getTab(currentFirstVisible);
  531. currentFirst.setVisible(false);
  532. currentFirst.recalculateCaptionWidth();
  533. return nextVisible;
  534. }
  535. private void recalculateCaptionWidths() {
  536. for (int i = 0; i < getTabCount(); ++i) {
  537. getTab(i).recalculateCaptionWidth();
  538. }
  539. }
  540. }
  541. // TODO using the CLASSNAME directly makes primaryStyleName for TabSheet of
  542. // very limited use - all use of style names should be refactored in the
  543. // future
  544. public static final String CLASSNAME = TabsheetState.PRIMARY_STYLE_NAME;
  545. public static final String TABS_CLASSNAME = CLASSNAME + "-tabcontainer";
  546. public static final String SCROLLER_CLASSNAME = CLASSNAME + "-scroller";
  547. /** For internal use only. May be removed or replaced in the future. */
  548. // tabbar and 'scroller' container
  549. public final Element tabs;
  550. /**
  551. * The tabindex property (position in the browser's focus cycle.) Named like
  552. * this to avoid confusion with activeTabIndex.
  553. */
  554. int tabulatorIndex = 0;
  555. private static final FocusImpl focusImpl = FocusImpl.getFocusImplForPanel();
  556. // tab-scroller element
  557. private final Element scroller;
  558. // tab-scroller next button element
  559. private final Element scrollerNext;
  560. // tab-scroller prev button element
  561. private final Element scrollerPrev;
  562. /**
  563. * The index of the first visible tab (when scrolled)
  564. */
  565. private int scrollerIndex = 0;
  566. final TabBar tb = new TabBar(this);
  567. /** For internal use only. May be removed or replaced in the future. */
  568. protected final VTabsheetPanel tabPanel = new VTabsheetPanel();
  569. /** For internal use only. May be removed or replaced in the future. */
  570. public final Element contentNode;
  571. private final Element deco;
  572. /** For internal use only. May be removed or replaced in the future. */
  573. public boolean waitingForResponse;
  574. private String currentStyle;
  575. /**
  576. * @return Whether the tab could be selected or not.
  577. */
  578. private boolean canSelectTab(final int tabIndex) {
  579. Tab tab = tb.getTab(tabIndex);
  580. if (getApplicationConnection() == null || disabled
  581. || waitingForResponse) {
  582. return false;
  583. }
  584. if (!tab.isEnabledOnServer() || tab.isHiddenOnServer()) {
  585. return false;
  586. }
  587. // Note that we return true when tabIndex == activeTabIndex; the active
  588. // tab could be selected, it's just a no-op.
  589. return true;
  590. }
  591. /**
  592. * Load the content of a tab of the provided index.
  593. *
  594. * @param index
  595. * of the tab to load
  596. *
  597. * @return true if the specified sheet gets loaded, otherwise false.
  598. */
  599. public boolean loadTabSheet(int tabIndex) {
  600. if (activeTabIndex != tabIndex && canSelectTab(tabIndex)) {
  601. tb.selectTab(tabIndex);
  602. activeTabIndex = tabIndex;
  603. addStyleDependentName("loading");
  604. // Hide the current contents so a loading indicator can be shown
  605. // instead
  606. getCurrentlyDisplayedWidget().getElement().getParentElement()
  607. .getStyle().setVisibility(Visibility.HIDDEN);
  608. getRpcProxy().setSelected(tabKeys.get(tabIndex).toString());
  609. waitingForResponse = true;
  610. tb.getTab(tabIndex).focus(); // move keyboard focus to active tab
  611. return true;
  612. }
  613. return false;
  614. }
  615. /**
  616. * Returns the currently displayed widget in the tab panel.
  617. *
  618. * @since 7.2
  619. * @return currently displayed content widget
  620. */
  621. public Widget getCurrentlyDisplayedWidget() {
  622. return tabPanel.getWidget(tabPanel.getVisibleWidget());
  623. }
  624. /**
  625. * Returns the client to server RPC proxy for the tabsheet.
  626. *
  627. * @since 7.2
  628. * @return RPC proxy
  629. */
  630. protected TabsheetServerRpc getRpcProxy() {
  631. return connector.getRpcProxy(TabsheetServerRpc.class);
  632. }
  633. /**
  634. * For internal use only.
  635. *
  636. * Avoid using this method directly and use appropriate superclass methods
  637. * where applicable.
  638. *
  639. * @deprecated since 7.2 - use more specific methods instead (getRpcProxy(),
  640. * getConnectorForWidget(Widget) etc.)
  641. * @return ApplicationConnection
  642. */
  643. @Deprecated
  644. public ApplicationConnection getApplicationConnection() {
  645. return client;
  646. }
  647. private VTooltip getVTooltip() {
  648. return getApplicationConnection().getVTooltip();
  649. }
  650. public void tabSizeMightHaveChanged(Tab tab) {
  651. // icon onloads may change total width of tabsheet
  652. if (isDynamicWidth()) {
  653. updateDynamicWidth();
  654. }
  655. updateTabScroller();
  656. }
  657. void sendTabClosedEvent(int tabIndex) {
  658. getRpcProxy().closeTab(tabKeys.get(tabIndex));
  659. }
  660. public VTabsheet() {
  661. super(CLASSNAME);
  662. // Tab scrolling
  663. getElement().getStyle().setOverflow(Overflow.HIDDEN);
  664. tabs = DOM.createDiv();
  665. DOM.setElementProperty(tabs, "className", TABS_CLASSNAME);
  666. Roles.getTablistRole().set(tabs);
  667. Roles.getTablistRole().setAriaLiveProperty(tabs, LiveValue.OFF);
  668. scroller = DOM.createDiv();
  669. Roles.getTablistRole().setAriaHiddenState(scroller, true);
  670. DOM.setElementProperty(scroller, "className", SCROLLER_CLASSNAME);
  671. scrollerPrev = DOM.createButton();
  672. scrollerPrev.setTabIndex(-1);
  673. DOM.setElementProperty(scrollerPrev, "className", SCROLLER_CLASSNAME
  674. + "Prev");
  675. Roles.getTablistRole().setAriaHiddenState(scrollerPrev, true);
  676. DOM.sinkEvents(scrollerPrev, Event.ONCLICK | Event.ONMOUSEDOWN);
  677. scrollerNext = DOM.createButton();
  678. scrollerNext.setTabIndex(-1);
  679. DOM.setElementProperty(scrollerNext, "className", SCROLLER_CLASSNAME
  680. + "Next");
  681. Roles.getTablistRole().setAriaHiddenState(scrollerNext, true);
  682. DOM.sinkEvents(scrollerNext, Event.ONCLICK | Event.ONMOUSEDOWN);
  683. DOM.appendChild(getElement(), tabs);
  684. // Tabs
  685. tabPanel.setStyleName(CLASSNAME + "-tabsheetpanel");
  686. contentNode = DOM.createDiv();
  687. Roles.getTabpanelRole().set(contentNode);
  688. deco = DOM.createDiv();
  689. addStyleDependentName("loading"); // Indicate initial progress
  690. tb.setStyleName(CLASSNAME + "-tabs");
  691. DOM.setElementProperty(contentNode, "className", CLASSNAME + "-content");
  692. DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
  693. add(tb, tabs);
  694. DOM.appendChild(scroller, scrollerPrev);
  695. DOM.appendChild(scroller, scrollerNext);
  696. DOM.appendChild(getElement(), contentNode);
  697. add(tabPanel, contentNode);
  698. DOM.appendChild(getElement(), deco);
  699. DOM.appendChild(tabs, scroller);
  700. // TODO Use for Safari only. Fix annoying 1px first cell in TabBar.
  701. // DOM.setStyleAttribute(DOM.getFirstChild(DOM.getFirstChild(DOM
  702. // .getFirstChild(tb.getElement()))), "display", "none");
  703. }
  704. @Override
  705. public void onBrowserEvent(Event event) {
  706. com.google.gwt.dom.client.Element eventTarget = DOM
  707. .eventGetTarget(event);
  708. if (event.getTypeInt() == Event.ONCLICK) {
  709. // Tab scrolling
  710. if (eventTarget == scrollerPrev || eventTarget == scrollerNext) {
  711. scrollAccordingToScrollTarget(eventTarget);
  712. event.stopPropagation();
  713. }
  714. } else if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  715. if (eventTarget == scrollerPrev || eventTarget == scrollerNext) {
  716. // In case the focus was previously on a Tab, we need to cancel
  717. // the upcoming blur on the Tab which will follow this mouse
  718. // down event.
  719. focusBlurManager.cancelNextBlurSchedule();
  720. return;
  721. }
  722. }
  723. super.onBrowserEvent(event);
  724. }
  725. /*
  726. * Scroll the tab bar according to the last scrollTarget (the scroll button
  727. * pressed).
  728. */
  729. private void scrollAccordingToScrollTarget(
  730. com.google.gwt.dom.client.Element scrollTarget) {
  731. if (scrollTarget == null) {
  732. return;
  733. }
  734. int newFirstIndex = -1;
  735. // Scroll left.
  736. if (isScrolledTabs() && scrollTarget == scrollerPrev) {
  737. newFirstIndex = tb.scrollLeft(scrollerIndex);
  738. // Scroll right.
  739. } else if (isClippedTabs() && scrollTarget == scrollerNext) {
  740. newFirstIndex = tb.scrollRight(scrollerIndex);
  741. }
  742. if (newFirstIndex != -1) {
  743. scrollerIndex = newFirstIndex;
  744. updateTabScroller();
  745. }
  746. // For this to work well, make sure the method gets called only from
  747. // user events.
  748. selectionHandler.focusTabAtIndex(scrollerIndex);
  749. }
  750. /**
  751. * Checks if the tab with the selected index has been scrolled out of the
  752. * view (on the left side).
  753. *
  754. * @param index
  755. * @return
  756. */
  757. private boolean scrolledOutOfView(int index) {
  758. return scrollerIndex > index;
  759. }
  760. /** For internal use only. May be removed or replaced in the future. */
  761. public void handleStyleNames(AbstractComponentState state) {
  762. // Add proper stylenames for all elements (easier to prevent unwanted
  763. // style inheritance)
  764. if (ComponentStateUtil.hasStyles(state)) {
  765. final List<String> styles = state.styles;
  766. if (currentStyle == null || !currentStyle.equals(styles.toString())) {
  767. currentStyle = styles.toString();
  768. final String tabsBaseClass = TABS_CLASSNAME;
  769. String tabsClass = tabsBaseClass;
  770. final String contentBaseClass = CLASSNAME + "-content";
  771. String contentClass = contentBaseClass;
  772. final String decoBaseClass = CLASSNAME + "-deco";
  773. String decoClass = decoBaseClass;
  774. for (String style : styles) {
  775. tb.addStyleDependentName(style);
  776. tabsClass += " " + tabsBaseClass + "-" + style;
  777. contentClass += " " + contentBaseClass + "-" + style;
  778. decoClass += " " + decoBaseClass + "-" + style;
  779. }
  780. DOM.setElementProperty(tabs, "className", tabsClass);
  781. DOM.setElementProperty(contentNode, "className", contentClass);
  782. DOM.setElementProperty(deco, "className", decoClass);
  783. }
  784. } else {
  785. tb.setStyleName(CLASSNAME + "-tabs");
  786. DOM.setElementProperty(tabs, "className", TABS_CLASSNAME);
  787. DOM.setElementProperty(contentNode, "className", CLASSNAME
  788. + "-content");
  789. DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
  790. }
  791. }
  792. /** For internal use only. May be removed or replaced in the future. */
  793. public void updateDynamicWidth() {
  794. // Find width consumed by tabs
  795. TableCellElement spacerCell = ((TableElement) tb.getElement().cast())
  796. .getRows().getItem(0).getCells().getItem(tb.getTabCount());
  797. int spacerWidth = spacerCell.getOffsetWidth();
  798. DivElement div = (DivElement) spacerCell.getFirstChildElement();
  799. int spacerMinWidth = spacerCell.getOffsetWidth() - div.getOffsetWidth();
  800. int tabsWidth = tb.getOffsetWidth() - spacerWidth + spacerMinWidth;
  801. // Find content width
  802. Style style = tabPanel.getElement().getStyle();
  803. String overflow = style.getProperty("overflow");
  804. style.setProperty("overflow", "hidden");
  805. style.setPropertyPx("width", tabsWidth);
  806. boolean hasTabs = tabPanel.getWidgetCount() > 0;
  807. Style wrapperstyle = null;
  808. if (hasTabs) {
  809. wrapperstyle = getCurrentlyDisplayedWidget().getElement()
  810. .getParentElement().getStyle();
  811. wrapperstyle.setPropertyPx("width", tabsWidth);
  812. }
  813. // Get content width from actual widget
  814. int contentWidth = 0;
  815. if (hasTabs) {
  816. contentWidth = getCurrentlyDisplayedWidget().getOffsetWidth();
  817. }
  818. style.setProperty("overflow", overflow);
  819. // Set widths to max(tabs,content)
  820. if (tabsWidth < contentWidth) {
  821. tabsWidth = contentWidth;
  822. }
  823. int outerWidth = tabsWidth + getContentAreaBorderWidth();
  824. tabs.getStyle().setPropertyPx("width", outerWidth);
  825. style.setPropertyPx("width", tabsWidth);
  826. if (hasTabs) {
  827. wrapperstyle.setPropertyPx("width", tabsWidth);
  828. }
  829. contentNode.getStyle().setPropertyPx("width", tabsWidth);
  830. super.setWidth(outerWidth + "px");
  831. updateOpenTabSize();
  832. }
  833. @Override
  834. public void renderTab(final TabState tabState, int index) {
  835. Tab tab = tb.getTab(index);
  836. if (tab == null) {
  837. tab = tb.addTab();
  838. }
  839. tab.updateFromState(tabState);
  840. tab.setEnabledOnServer((!disabledTabKeys.contains(tabKeys.get(index))));
  841. tab.setHiddenOnServer(!tabState.visible);
  842. if (scrolledOutOfView(index)) {
  843. // Should not set tabs visible if they are scrolled out of view
  844. tab.setVisible(false);
  845. } else {
  846. tab.setVisible(tabState.visible);
  847. }
  848. /*
  849. * Force the width of the caption container so the content will not wrap
  850. * and tabs won't be too narrow in certain browsers
  851. */
  852. tab.recalculateCaptionWidth();
  853. }
  854. /**
  855. * @deprecated as of 7.1, VTabsheet only keeps the active tab in the DOM
  856. * without any place holders.
  857. */
  858. @Deprecated
  859. public class PlaceHolder extends VLabel {
  860. public PlaceHolder() {
  861. super("");
  862. }
  863. }
  864. /**
  865. * Renders the widget content for a tab sheet.
  866. *
  867. * @param newWidget
  868. */
  869. public void renderContent(Widget newWidget) {
  870. assert tabPanel.getWidgetCount() <= 1;
  871. if (null == newWidget) {
  872. newWidget = new SimplePanel();
  873. }
  874. if (tabPanel.getWidgetCount() == 0) {
  875. tabPanel.add(newWidget);
  876. } else if (tabPanel.getWidget(0) != newWidget) {
  877. tabPanel.remove(0);
  878. tabPanel.add(newWidget);
  879. }
  880. assert tabPanel.getWidgetCount() <= 1;
  881. // There's never any other index than 0, but maintaining API for now
  882. tabPanel.showWidget(0);
  883. VTabsheet.this.iLayout();
  884. updateOpenTabSize();
  885. VTabsheet.this.removeStyleDependentName("loading");
  886. }
  887. /**
  888. * Recalculates the sizes of tab captions, causing the tabs to be rendered
  889. * the correct size.
  890. */
  891. private void updateTabCaptionSizes() {
  892. for (int tabIx = 0; tabIx < tb.getTabCount(); tabIx++) {
  893. tb.getTab(tabIx).recalculateCaptionWidth();
  894. }
  895. }
  896. /** For internal use only. May be removed or replaced in the future. */
  897. public void updateContentNodeHeight() {
  898. if (!isDynamicHeight()) {
  899. int contentHeight = getOffsetHeight();
  900. contentHeight -= DOM.getElementPropertyInt(deco, "offsetHeight");
  901. contentHeight -= tb.getOffsetHeight();
  902. if (contentHeight < 0) {
  903. contentHeight = 0;
  904. }
  905. // Set proper values for content element
  906. contentNode.getStyle().setHeight(contentHeight, Unit.PX);
  907. } else {
  908. contentNode.getStyle().clearHeight();
  909. }
  910. }
  911. /**
  912. * Run internal layouting.
  913. */
  914. public void iLayout() {
  915. updateTabScroller();
  916. updateTabCaptionSizes();
  917. }
  918. /**
  919. * Sets the size of the visible tab (component). As the tab is set to
  920. * position: absolute (to work around a firefox flickering bug) we must keep
  921. * this up-to-date by hand.
  922. * <p>
  923. * For internal use only. May be removed or replaced in the future.
  924. */
  925. public void updateOpenTabSize() {
  926. /*
  927. * The overflow=auto element must have a height specified, otherwise it
  928. * will be just as high as the contents and no scrollbars will appear
  929. */
  930. int height = -1;
  931. int width = -1;
  932. int minWidth = 0;
  933. if (!isDynamicHeight()) {
  934. height = contentNode.getOffsetHeight();
  935. }
  936. if (!isDynamicWidth()) {
  937. width = contentNode.getOffsetWidth() - getContentAreaBorderWidth();
  938. } else {
  939. /*
  940. * If the tabbar is wider than the content we need to use the tabbar
  941. * width as minimum width so scrollbars get placed correctly (at the
  942. * right edge).
  943. */
  944. minWidth = tb.getOffsetWidth() - getContentAreaBorderWidth();
  945. }
  946. tabPanel.fixVisibleTabSize(width, height, minWidth);
  947. }
  948. /**
  949. * Layouts the tab-scroller elements, and applies styles.
  950. */
  951. private void updateTabScroller() {
  952. if (!isDynamicWidth()) {
  953. tabs.getStyle().setWidth(100, Unit.PCT);
  954. }
  955. // Make sure scrollerIndex is valid
  956. if (scrollerIndex < 0 || scrollerIndex > tb.getTabCount()) {
  957. scrollerIndex = tb.getFirstVisibleTab();
  958. } else if (tb.getTabCount() > 0
  959. && tb.getTab(scrollerIndex).isHiddenOnServer()) {
  960. scrollerIndex = tb.getNextVisibleTab(scrollerIndex);
  961. }
  962. boolean scrolled = isScrolledTabs();
  963. boolean clipped = isClippedTabs();
  964. if (tb.getTabCount() > 0 && tb.isVisible() && (scrolled || clipped)) {
  965. scroller.getStyle().clearDisplay();
  966. DOM.setElementProperty(scrollerPrev, "className",
  967. SCROLLER_CLASSNAME + (scrolled ? "Prev" : "Prev-disabled"));
  968. DOM.setElementProperty(scrollerNext, "className",
  969. SCROLLER_CLASSNAME + (clipped ? "Next" : "Next-disabled"));
  970. // the active tab should be focusable if and only if it is visible
  971. boolean isActiveTabVisible = scrollerIndex <= activeTabIndex
  972. && !isClipped(tb.selected);
  973. tb.selected.setTabulatorIndex(isActiveTabVisible ? tabulatorIndex
  974. : -1);
  975. } else {
  976. scroller.getStyle().setDisplay(Display.NONE);
  977. }
  978. if (BrowserInfo.get().isSafari()) {
  979. /*
  980. * another hack for webkits. tabscroller sometimes drops without
  981. * "shaking it" reproducable in
  982. * com.vaadin.tests.components.tabsheet.TabSheetIcons
  983. */
  984. final Style style = scroller.getStyle();
  985. style.setProperty("whiteSpace", "normal");
  986. Scheduler.get().scheduleDeferred(new Command() {
  987. @Override
  988. public void execute() {
  989. style.setProperty("whiteSpace", "");
  990. }
  991. });
  992. }
  993. }
  994. /** For internal use only. May be removed or replaced in the future. */
  995. public void showAllTabs() {
  996. scrollerIndex = tb.getFirstVisibleTab();
  997. for (int i = 0; i < tb.getTabCount(); i++) {
  998. Tab t = tb.getTab(i);
  999. if (!t.isHiddenOnServer()) {
  1000. t.setVisible(true);
  1001. }
  1002. }
  1003. }
  1004. private boolean isScrolledTabs() {
  1005. return scrollerIndex > tb.getFirstVisibleTab();
  1006. }
  1007. private boolean isClippedTabs() {
  1008. return (tb.getOffsetWidth() - DOM.getElementPropertyInt((Element) tb
  1009. .getContainerElement().getLastChild().cast(), "offsetWidth")) > getOffsetWidth()
  1010. - (isScrolledTabs() ? scroller.getOffsetWidth() : 0);
  1011. }
  1012. private boolean isClipped(Tab tab) {
  1013. return tab.getAbsoluteLeft() + tab.getOffsetWidth() > getAbsoluteLeft()
  1014. + getOffsetWidth() - scroller.getOffsetWidth();
  1015. }
  1016. @Override
  1017. protected void clearPaintables() {
  1018. int i = tb.getTabCount();
  1019. while (i > 0) {
  1020. tb.removeTab(--i);
  1021. }
  1022. tabPanel.clear();
  1023. }
  1024. @Override
  1025. public Iterator<Widget> getWidgetIterator() {
  1026. return tabPanel.iterator();
  1027. }
  1028. /** For internal use only. May be removed or replaced in the future. */
  1029. public int getContentAreaBorderWidth() {
  1030. return Util.measureHorizontalBorder(contentNode);
  1031. }
  1032. @Override
  1033. public int getTabCount() {
  1034. return tb.getTabCount();
  1035. }
  1036. @Override
  1037. public ComponentConnector getTab(int index) {
  1038. if (tabPanel.getWidgetCount() > index) {
  1039. Widget widget = tabPanel.getWidget(index);
  1040. return getConnectorForWidget(widget);
  1041. }
  1042. return null;
  1043. }
  1044. @Override
  1045. public void removeTab(int index) {
  1046. tb.removeTab(index);
  1047. // Removing content from tp is handled by the connector
  1048. }
  1049. @Override
  1050. public void selectTab(int index) {
  1051. tb.selectTab(index);
  1052. }
  1053. @Override
  1054. public void focus() {
  1055. getActiveTab().focus();
  1056. }
  1057. public void blur() {
  1058. getActiveTab().blur();
  1059. }
  1060. /*
  1061. * Gets the active tab.
  1062. */
  1063. private Tab getActiveTab() {
  1064. return tb.getTab(activeTabIndex);
  1065. }
  1066. @Override
  1067. public void setConnector(AbstractComponentConnector connector) {
  1068. super.setConnector(connector);
  1069. focusBlurManager.connector = connector;
  1070. }
  1071. /*
  1072. * The focus and blur manager instance.
  1073. */
  1074. private FocusBlurManager focusBlurManager = new FocusBlurManager();
  1075. /*
  1076. * Generate the correct focus/blur events for the main TabSheet component
  1077. * (#14304).
  1078. *
  1079. * The TabSheet must fire one focus event when the user clicks on the tab
  1080. * bar (i.e. inner TabBar class) containing the Tabs or when the focus is
  1081. * provided to the TabSheet by any means. Also one blur event should be
  1082. * fired only when the user leaves the tab bar. After the user focus on the
  1083. * tab bar and before leaving it, no matter how many times he's pressing the
  1084. * Tabs or the scroll buttons, the TabSheet component should not fire any of
  1085. * those blur/focus events.
  1086. *
  1087. * The only focusable elements contained in the tab bar are the Tabs (see
  1088. * inner class Tab). The reason is the accessibility support.
  1089. *
  1090. * Having this in mind, the chosen solution path for our problem is to match
  1091. * a sequence of focus/blur events on the tabs, choose only the first focus
  1092. * and last blur events and pass only those further to the main component.
  1093. * Any consecutive blur/focus events on 2 Tabs must be ignored.
  1094. *
  1095. * Because in a blur event we don't know whether or not a focus will follow,
  1096. * we just defer a command initiated on the blur event to wait and see if
  1097. * any focus will appear. The command will be executed after the next focus,
  1098. * so if no focus was triggered in the mean while it'll submit the blur
  1099. * event to the main component, otherwise it'll do nothing, so the main
  1100. * component will not generate the blur..
  1101. */
  1102. private static class FocusBlurManager {
  1103. // The real tab with focus on it. If the focus goes to another element
  1104. // in the page this will be null.
  1105. private Tab focusedTab;
  1106. /*
  1107. * Gets the focused tab.
  1108. */
  1109. private Tab getFocusedTab() {
  1110. return focusedTab;
  1111. }
  1112. /*
  1113. * Sets the local field tracking the focused tab.
  1114. */
  1115. private void setFocusedTab(Tab focusedTab) {
  1116. this.focusedTab = focusedTab;
  1117. }
  1118. /*
  1119. * The ultimate focus/blur event dispatcher.
  1120. */
  1121. private AbstractComponentConnector connector;
  1122. /**
  1123. * Delegate method for the onFocus event occurring on Tab.
  1124. *
  1125. * @since 7.2.6
  1126. * @param newFocusTab
  1127. * the new focused tab.
  1128. * @see #onBlur(Tab)
  1129. */
  1130. public void onFocus(Tab newFocusTab) {
  1131. if (connector.hasEventListener(EventId.FOCUS)) {
  1132. // Send the focus event only first time when we focus on any
  1133. // tab. The focused tab will be reseted on the last blur.
  1134. if (focusedTab == null) {
  1135. connector.getRpcProxy(FocusAndBlurServerRpc.class).focus();
  1136. }
  1137. }
  1138. cancelLastBlurSchedule();
  1139. setFocusedTab(newFocusTab);
  1140. }
  1141. /**
  1142. * Delegate method for the onBlur event occurring on Tab.
  1143. *
  1144. * @param blurSource
  1145. * the source of the blur.
  1146. *
  1147. * @see #onFocus(Tab)
  1148. */
  1149. public void onBlur(Tab blurSource) {
  1150. if (focusedTab != null && focusedTab == blurSource) {
  1151. if (connector.hasEventListener(EventId.BLUR)) {
  1152. scheduleBlur(focusedTab);
  1153. }
  1154. }
  1155. }
  1156. /*
  1157. * The last blur command to be executed.
  1158. */
  1159. private BlurCommand blurCommand;
  1160. /*
  1161. * Execute the final blur command.
  1162. */
  1163. private class BlurCommand implements Command {
  1164. /*
  1165. * The blur source.
  1166. */
  1167. private Tab blurSource;
  1168. /**
  1169. * Create the blur command using the blur source.
  1170. *
  1171. * @param blurSource
  1172. * the source.
  1173. * @param focusedTabProvider
  1174. * provides the current focused tab.
  1175. */
  1176. public BlurCommand(Tab blurSource) {
  1177. this.blurSource = blurSource;
  1178. }
  1179. /**
  1180. * Stop the command from being executed.
  1181. *
  1182. * @since
  1183. */
  1184. public void stopSchedule() {
  1185. blurSource = null;
  1186. }
  1187. /**
  1188. * Schedule the command for a deferred execution.
  1189. *
  1190. * @since
  1191. */
  1192. public void scheduleDeferred() {
  1193. Scheduler.get().scheduleDeferred(this);
  1194. }
  1195. @Override
  1196. public void execute() {
  1197. Tab focusedTab = getFocusedTab();
  1198. if (blurSource == null) {
  1199. return;
  1200. }
  1201. // The focus didn't change since this blur triggered, so
  1202. // the new focused element is not a tab.
  1203. if (focusedTab == blurSource) {
  1204. // We're certain there's no focus anymore.
  1205. focusedTab.removeAssistiveDescription();
  1206. setFocusedTab(null);
  1207. connector.getRpcProxy(FocusAndBlurServerRpc.class).blur();
  1208. }
  1209. // Call this to set it to null and be consistent.
  1210. cancelLastBlurSchedule();
  1211. }
  1212. }
  1213. /*
  1214. * Schedule a new blur event for a deferred execution.
  1215. */
  1216. private void scheduleBlur(Tab blurSource) {
  1217. if (nextBlurScheduleCancelled) {
  1218. // This will set the stopNextBlurCommand back to false as well.
  1219. cancelLastBlurSchedule();
  1220. // Reset the status.
  1221. nextBlurScheduleCancelled = false;
  1222. return;
  1223. }
  1224. cancelLastBlurSchedule();
  1225. blurCommand = new BlurCommand(blurSource);
  1226. blurCommand.scheduleDeferred();
  1227. }
  1228. /**
  1229. * Remove the last blur deferred command from execution.
  1230. */
  1231. public void cancelLastBlurSchedule() {
  1232. if (blurCommand != null) {
  1233. blurCommand.stopSchedule();
  1234. blurCommand = null;
  1235. }
  1236. // We really want to make sure this flag gets reseted at any time
  1237. // when something interact with the blur manager and ther's no blur
  1238. // command scheduled (as we just canceled it).
  1239. nextBlurScheduleCancelled = false;
  1240. }
  1241. /**
  1242. * Cancel the next scheduled execution. This method must be called only
  1243. * from an event occurring before the onBlur event. It's the case of IE
  1244. * which doesn't trigger the focus event, so we're using this approach
  1245. * to cancel the next blur event prior it's execution, calling the
  1246. * method from mouse down event.
  1247. */
  1248. public void cancelNextBlurSchedule() {
  1249. // Make sure there's still no other command to be executed.
  1250. cancelLastBlurSchedule();
  1251. nextBlurScheduleCancelled = true;
  1252. }
  1253. /*
  1254. * Flag that the next deferred command won't get executed. This is
  1255. * useful in case of IE where the user focus event don't fire and we're
  1256. * using the mouse down event to track the focus. But the mouse down
  1257. * event triggers before the blur, so we need to cancel the deferred
  1258. * execution in advance.
  1259. */
  1260. private boolean nextBlurScheduleCancelled = false;
  1261. }
  1262. /*
  1263. * The tabs selection handler instance.
  1264. */
  1265. private final TabSelectionHandler selectionHandler = new TabSelectionHandler();
  1266. /*
  1267. * Handle the events for selecting the tabs.
  1268. */
  1269. private class TabSelectionHandler implements FocusHandler, BlurHandler,
  1270. KeyDownHandler, ClickHandler, MouseDownHandler {
  1271. /** For internal use only. May be removed or replaced in the future. */
  1272. // The current visible focused index.
  1273. private int focusedTabIndex = 0;
  1274. /**
  1275. * Register the tab to the selection handler.
  1276. *
  1277. * @param tab
  1278. * the tab to register.
  1279. */
  1280. public void registerTab(Tab tab) {
  1281. tab.addBlurHandler(this);
  1282. tab.addFocusHandler(this);
  1283. tab.addKeyDownHandler(this);
  1284. tab.addClickHandler(this);
  1285. tab.addMouseDownHandler(this);
  1286. }
  1287. @Override
  1288. public void onBlur(final BlurEvent event) {
  1289. getVTooltip().hideTooltip();
  1290. Object blurSource = event.getSource();
  1291. if (blurSource instanceof Tab) {
  1292. focusBlurManager.onBlur((Tab) blurSource);
  1293. }
  1294. }
  1295. @Override
  1296. public void onFocus(FocusEvent event) {
  1297. if (event.getSource() instanceof Tab) {
  1298. Tab focusSource = (Tab) event.getSource();
  1299. focusBlurManager.onFocus(focusSource);
  1300. if (focusSource.hasTooltip()) {
  1301. focusSource.setAssistiveDescription(getVTooltip()
  1302. .getUniqueId());
  1303. getVTooltip().showAssistive(focusSource.getTooltipInfo());
  1304. }
  1305. }
  1306. }
  1307. @Override
  1308. public void onClick(ClickEvent event) {
  1309. // IE doesn't trigger focus when click, so we need to make sure
  1310. // the previous blur deferred command will get killed.
  1311. focusBlurManager.cancelLastBlurSchedule();
  1312. TabCaption caption = (TabCaption) event.getSource();
  1313. Element targetElement = event.getNativeEvent().getEventTarget()
  1314. .cast();
  1315. // the tab should not be focused if the close button was clicked
  1316. if (targetElement == caption.getCloseButton()) {
  1317. return;
  1318. }
  1319. int index = tb.getWidgetIndex(caption.getParent());
  1320. tb.navigateTab(focusedTabIndex, index);
  1321. focusedTabIndex = index;
  1322. if (!loadTabSheet(index)) {
  1323. // This needs to be called at the end, as the activeTabIndex
  1324. // is set in the loadTabSheet.
  1325. focus();
  1326. }
  1327. }
  1328. @Override
  1329. public void onMouseDown(MouseDownEvent event) {
  1330. if (event.getSource() instanceof Tab) {
  1331. // IE doesn't trigger focus when click, so we need to make sure
  1332. // the
  1333. // next blur deferred command will get killed.
  1334. focusBlurManager.cancelNextBlurSchedule();
  1335. }
  1336. }
  1337. @Override
  1338. public void onKeyDown(KeyDownEvent event) {
  1339. if (event.getSource() instanceof Tab) {
  1340. int keycode = event.getNativeEvent().getKeyCode();
  1341. if (!event.isAnyModifierKeyDown()) {
  1342. if (keycode == getPreviousTabKey()) {
  1343. selectPreviousTab();
  1344. event.stopPropagation();
  1345. } else if (keycode == getNextTabKey()) {
  1346. selectNextTab();
  1347. event.stopPropagation();
  1348. } else if (keycode == getCloseTabKey()) {
  1349. Tab tab = tb.getTab(activeTabIndex);
  1350. if (tab.isClosable()) {
  1351. tab.onClose();
  1352. }
  1353. } else if (keycode == getSelectTabKey()) {
  1354. loadTabSheet(focusedTabIndex);
  1355. // Prevent the page from scrolling when hitting space
  1356. // (select key) to select the current tab.
  1357. event.preventDefault();
  1358. }
  1359. }
  1360. }
  1361. }
  1362. /*
  1363. * Left arrow key selection.
  1364. */
  1365. private void selectPreviousTab() {
  1366. int newTabIndex = focusedTabIndex;
  1367. // Find the previous visible and enabled tab if any.
  1368. do {
  1369. newTabIndex--;
  1370. } while (newTabIndex >= 0 && !canSelectTab(newTabIndex));
  1371. if (newTabIndex >= 0) {
  1372. keySelectTab(newTabIndex);
  1373. }
  1374. }
  1375. /*
  1376. * Right arrow key selection.
  1377. */
  1378. private void selectNextTab() {
  1379. int newTabIndex = focusedTabIndex;
  1380. // Find the next visible and enabled tab if any.
  1381. do {
  1382. newTabIndex++;
  1383. } while (newTabIndex < getTabCount() && !canSelectTab(newTabIndex));
  1384. if (newTabIndex < getTabCount()) {
  1385. keySelectTab(newTabIndex);
  1386. }
  1387. }
  1388. /*
  1389. * Select the specified tab using left/right key.
  1390. */
  1391. private void keySelectTab(int newTabIndex) {
  1392. Tab tab = tb.getTab(newTabIndex);
  1393. if (tab == null) {
  1394. return;
  1395. }
  1396. // Focus the tab, otherwise the selected one will loose focus and
  1397. // TabSheet will get blurred.
  1398. focusTabAtIndex(newTabIndex);
  1399. tb.navigateTab(focusedTabIndex, newTabIndex);
  1400. focusedTabIndex = newTabIndex;
  1401. }
  1402. /**
  1403. * Focus the specified tab. Make sure to call this only from user
  1404. * events, otherwise will break things.
  1405. *
  1406. * @param tabIndex
  1407. * the index of the tab to set.
  1408. */
  1409. void focusTabAtIndex(int tabIndex) {
  1410. Tab tabToFocus = tb.getTab(tabIndex);
  1411. if (tabToFocus != null) {
  1412. tabToFocus.focus();
  1413. }
  1414. }
  1415. }
  1416. /**
  1417. * @return The key code of the keyboard shortcut that selects the previous
  1418. * tab in a focused tabsheet.
  1419. */
  1420. protected int getPreviousTabKey() {
  1421. return KeyCodes.KEY_LEFT;
  1422. }
  1423. /**
  1424. * Gets the key to activate the selected tab when navigating using
  1425. * previous/next (left/right) keys.
  1426. *
  1427. * @return the key to activate the selected tab.
  1428. *
  1429. * @see #getNextTabKey()
  1430. * @see #getPreviousTabKey()
  1431. */
  1432. protected int getSelectTabKey() {
  1433. return KeyCodes.KEY_SPACE;
  1434. }
  1435. /**
  1436. * @return The key code of the keyboard shortcut that selects the next tab
  1437. * in a focused tabsheet.
  1438. */
  1439. protected int getNextTabKey() {
  1440. return KeyCodes.KEY_RIGHT;
  1441. }
  1442. /**
  1443. * @return The key code of the keyboard shortcut that closes the currently
  1444. * selected tab in a focused tabsheet.
  1445. */
  1446. protected int getCloseTabKey() {
  1447. return KeyCodes.KEY_DELETE;
  1448. }
  1449. private void scrollIntoView(Tab tab) {
  1450. if (!tab.isHiddenOnServer()) {
  1451. // Check for visibility first as clipped tabs to the right are
  1452. // always visible.
  1453. // On IE8 a tab with false visibility would have the bounds of the
  1454. // full TabBar.
  1455. if (!tab.isVisible()) {
  1456. while (!tab.isVisible()) {
  1457. scrollerIndex = tb.scrollLeft(scrollerIndex);
  1458. }
  1459. updateTabScroller();
  1460. } else if (isClipped(tab)) {
  1461. while (isClipped(tab) && scrollerIndex != -1) {
  1462. scrollerIndex = tb.scrollRight(scrollerIndex);
  1463. }
  1464. updateTabScroller();
  1465. }
  1466. }
  1467. }
  1468. /**
  1469. * Makes tab bar visible.
  1470. *
  1471. * @since 7.2
  1472. */
  1473. public void showTabs() {
  1474. tb.setVisible(true);
  1475. removeStyleName(CLASSNAME + "-hidetabs");
  1476. tb.recalculateCaptionWidths();
  1477. }
  1478. /**
  1479. * Makes tab bar invisible.
  1480. *
  1481. * @since 7.2
  1482. */
  1483. public void hideTabs() {
  1484. tb.setVisible(false);
  1485. addStyleName(CLASSNAME + "-hidetabs");
  1486. }
  1487. /** Matches tab[ix] - used for extracting the index of the targeted tab */
  1488. private static final RegExp SUBPART_TAB_REGEXP = RegExp
  1489. .compile("tab\\[(\\d+)](.*)");
  1490. @Override
  1491. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  1492. if ("tabpanel".equals(subPart)) {
  1493. return DOM.asOld(tabPanel.getElement().getFirstChildElement());
  1494. } else if (SUBPART_TAB_REGEXP.test(subPart)) {
  1495. MatchResult result = SUBPART_TAB_REGEXP.exec(subPart);
  1496. int tabIx = Integer.valueOf(result.getGroup(1));
  1497. Tab tab = tb.getTab(tabIx);
  1498. if (tab != null) {
  1499. if ("/close".equals(result.getGroup(2))) {
  1500. if (tab.isClosable()) {
  1501. return tab.tabCaption.getCloseButton();
  1502. }
  1503. } else {
  1504. return tab.tabCaption.getElement();
  1505. }
  1506. }
  1507. }
  1508. return null;
  1509. }
  1510. @Override
  1511. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  1512. if (tabPanel.getElement().equals(subElement.getParentElement())
  1513. || tabPanel.getElement().equals(subElement)) {
  1514. return "tabpanel";
  1515. } else {
  1516. for (int i = 0; i < tb.getTabCount(); ++i) {
  1517. Tab tab = tb.getTab(i);
  1518. if (tab.isClosable()
  1519. && tab.tabCaption.getCloseButton().isOrHasChild(
  1520. subElement)) {
  1521. return "tab[" + i + "]/close";
  1522. } else if (tab.getElement().isOrHasChild(subElement)) {
  1523. return "tab[" + i + "]";
  1524. }
  1525. }
  1526. }
  1527. return null;
  1528. }
  1529. }