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.

VMenuBar.java 64KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.LinkedList;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Queue;
  23. import com.google.gwt.core.client.GWT;
  24. import com.google.gwt.dom.client.Element;
  25. import com.google.gwt.dom.client.Style;
  26. import com.google.gwt.dom.client.Style.Overflow;
  27. import com.google.gwt.dom.client.Style.Unit;
  28. import com.google.gwt.event.dom.client.FocusEvent;
  29. import com.google.gwt.event.dom.client.FocusHandler;
  30. import com.google.gwt.event.dom.client.KeyCodes;
  31. import com.google.gwt.event.dom.client.KeyDownEvent;
  32. import com.google.gwt.event.dom.client.KeyDownHandler;
  33. import com.google.gwt.event.dom.client.KeyPressEvent;
  34. import com.google.gwt.event.dom.client.KeyPressHandler;
  35. import com.google.gwt.event.dom.client.MouseOutEvent;
  36. import com.google.gwt.event.dom.client.MouseOutHandler;
  37. import com.google.gwt.event.dom.client.MouseOverEvent;
  38. import com.google.gwt.event.dom.client.MouseOverHandler;
  39. import com.google.gwt.event.logical.shared.CloseEvent;
  40. import com.google.gwt.event.logical.shared.CloseHandler;
  41. import com.google.gwt.user.client.Command;
  42. import com.google.gwt.user.client.DOM;
  43. import com.google.gwt.user.client.Event;
  44. import com.google.gwt.user.client.Timer;
  45. import com.google.gwt.user.client.ui.HasHTML;
  46. import com.google.gwt.user.client.ui.PopupPanel;
  47. import com.google.gwt.user.client.ui.RootPanel;
  48. import com.google.gwt.user.client.ui.Widget;
  49. import com.google.web.bindery.event.shared.HandlerRegistration;
  50. import com.vaadin.client.ApplicationConnection;
  51. import com.vaadin.client.BrowserInfo;
  52. import com.vaadin.client.LayoutManager;
  53. import com.vaadin.client.TooltipInfo;
  54. import com.vaadin.client.UIDL;
  55. import com.vaadin.client.Util;
  56. import com.vaadin.client.WidgetUtil;
  57. import com.vaadin.client.extensions.EventTrigger;
  58. import com.vaadin.shared.ui.ContentMode;
  59. import com.vaadin.shared.ui.menubar.MenuBarConstants;
  60. public class VMenuBar extends FocusableFlowPanel implements
  61. CloseHandler<PopupPanel>, KeyPressHandler, KeyDownHandler, FocusHandler,
  62. SubPartAware, MouseOutHandler, MouseOverHandler, EventTrigger {
  63. // The hierarchy of VMenuBar is a bit weird as VMenuBar is the Paintable,
  64. // used for the root menu but also used for the sub menus.
  65. /** Set the CSS class name to allow styling. */
  66. public static final String CLASSNAME = "v-menubar";
  67. public static final String SUBMENU_CLASSNAME_PREFIX = "-submenu";
  68. /**
  69. * For server connections.
  70. * <p>
  71. * For internal use only. May be removed or replaced in the future.
  72. */
  73. public String uidlId;
  74. /** For internal use only. May be removed or replaced in the future. */
  75. public ApplicationConnection client;
  76. /** For internal use only. May be removed or replaced in the future. */
  77. public final VMenuBar hostReference = this;
  78. /** For internal use only. May be removed or replaced in the future. */
  79. public CustomMenuItem moreItem = null;
  80. /** For internal use only. May be removed or replaced in the future. */
  81. public VMenuBar collapsedRootItems;
  82. /**
  83. * An empty command to be used when the item has no command associated
  84. * <p>
  85. * For internal use only. May be removed or replaced in the future.
  86. */
  87. public static final Command emptyCommand = null;
  88. protected boolean subMenu;
  89. protected List<CustomMenuItem> items;
  90. protected Element containerElement;
  91. protected VOverlay popup;
  92. protected VMenuBar visibleChildMenu;
  93. protected boolean menuVisible = false;
  94. protected VMenuBar parentMenu;
  95. protected CustomMenuItem selected;
  96. /** For internal use only. May be removed or replaced in the future. */
  97. public boolean enabled = true;
  98. /** For internal use only. May be removed or replaced in the future. */
  99. private boolean ignoreFocus = false;
  100. private VLazyExecutor iconLoadedExecutioner = new VLazyExecutor(100,
  101. () -> iLayout(true));
  102. /** For internal use only. May be removed or replaced in the future. */
  103. public boolean openRootOnHover;
  104. /** For internal use only. May be removed or replaced in the future. */
  105. public boolean htmlContentAllowed;
  106. private Map<String, List<Command>> triggers = new HashMap<>();
  107. public VMenuBar() {
  108. // Create an empty horizontal menubar
  109. this(false, null);
  110. // Navigation is only handled by the root bar
  111. addFocusHandler(this);
  112. /*
  113. * Firefox auto-repeat works correctly only if we use a key press
  114. * handler, other browsers handle it correctly when using a key down
  115. * handler
  116. */
  117. if (BrowserInfo.get().isGecko()) {
  118. addKeyPressHandler(this);
  119. } else {
  120. addKeyDownHandler(this);
  121. }
  122. getElement().setAttribute("tabindex", "0");
  123. }
  124. public VMenuBar(boolean subMenu, VMenuBar parentMenu) {
  125. items = new ArrayList<>();
  126. popup = null;
  127. visibleChildMenu = null;
  128. this.subMenu = subMenu;
  129. containerElement = getElement();
  130. sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT
  131. | Event.ONLOAD);
  132. if (parentMenu == null) {
  133. // Root menu
  134. setStyleName(CLASSNAME);
  135. containerElement.setAttribute("role", "menubar");
  136. } else {
  137. // Child menus inherits style name
  138. setStyleName(parentMenu.getStyleName());
  139. containerElement.setAttribute("role", "menu");
  140. }
  141. getElement().setAttribute("tabindex", "-1");
  142. }
  143. @Override
  144. public void setStyleName(String style) {
  145. super.setStyleName(style);
  146. updateStyleNames();
  147. }
  148. @Override
  149. public void setStylePrimaryName(String style) {
  150. super.setStylePrimaryName(style);
  151. updateStyleNames();
  152. }
  153. protected void updateStyleNames() {
  154. String primaryStyleName = getParentMenu() != null
  155. ? getParentMenu().getStylePrimaryName()
  156. : getStylePrimaryName();
  157. // Reset the style name for all the items
  158. for (CustomMenuItem item : items) {
  159. item.refreshPrimaryStyleNameAndAriaAttributes(primaryStyleName);
  160. }
  161. if (subMenu
  162. && !getStylePrimaryName().endsWith(SUBMENU_CLASSNAME_PREFIX)) {
  163. /*
  164. * Sub-menus should get the sub-menu prefix
  165. */
  166. super.setStylePrimaryName(
  167. primaryStyleName + SUBMENU_CLASSNAME_PREFIX);
  168. }
  169. }
  170. @Override
  171. protected void onDetach() {
  172. super.onDetach();
  173. if (!subMenu) {
  174. setSelected(null);
  175. hideChildren();
  176. menuVisible = false;
  177. }
  178. }
  179. void updateSize() {
  180. // Take from setWidth
  181. if (!subMenu) {
  182. // Only needed for root level menu
  183. hideChildren();
  184. setSelected(null);
  185. menuVisible = false;
  186. }
  187. }
  188. /**
  189. * Build the HTML content for a menu item.
  190. * <p>
  191. * For internal use only. May be removed or replaced in the future.
  192. */
  193. public String buildItemHTML(UIDL item) {
  194. return buildItemHTML(item.hasAttribute("separator"),
  195. item.getChildCount() > 0, item.getStringAttribute("icon"),
  196. item.getStringAttribute("text"));
  197. }
  198. /**
  199. * Build the HTML content for a menu item.
  200. * <p>
  201. * For internal use only. May be removed or replaced in the future.
  202. *
  203. * @param separator
  204. * the menu item is separator
  205. * @param subMenu
  206. * the menu item contains submenu
  207. * @param iconUrl
  208. * the menu item icon URL or {@code null}
  209. * @param text
  210. * the menu item text. May not be {@code null}
  211. */
  212. public String buildItemHTML(boolean separator, boolean subMenu,
  213. String iconUrl, String text) {
  214. // Construct html from the text and the optional icon
  215. StringBuilder itemHTML = new StringBuilder();
  216. if (separator) {
  217. itemHTML.append("<span>---</span>");
  218. } else {
  219. // Add submenu indicator
  220. if (subMenu) {
  221. String bgStyle = "";
  222. itemHTML.append("<span class=\"" + getStylePrimaryName()
  223. + "-submenu-indicator\"" + bgStyle
  224. + " aria-hidden=\"true\">&#x25BA;</span>");
  225. }
  226. itemHTML.append("<span class=\"" + getStylePrimaryName()
  227. + "-menuitem-caption\">");
  228. Icon icon = client.getIcon(iconUrl);
  229. if (icon != null) {
  230. itemHTML.append(icon.getElement().getString());
  231. }
  232. String itemText = text;
  233. if (!htmlContentAllowed) {
  234. itemText = WidgetUtil.escapeHTML(itemText);
  235. }
  236. itemHTML.append(itemText);
  237. itemHTML.append("</span>");
  238. }
  239. return itemHTML.toString();
  240. }
  241. /**
  242. * This is called by the items in the menu and it communicates the
  243. * information to the server.
  244. *
  245. * @param clickedItemId
  246. * id of the item that was clicked
  247. */
  248. public void onMenuClick(int clickedItemId) {
  249. // Updating the state to the server can not be done before
  250. // the server connection is known, i.e., before updateFromUIDL()
  251. // has been called.
  252. if (uidlId != null && client != null) {
  253. // Communicate the user interaction parameters to server. This call
  254. // will initiate an AJAX request to the server.
  255. client.updateVariable(uidlId, "clickedId", clickedItemId, true);
  256. }
  257. }
  258. /* Widget methods */
  259. /**
  260. * Returns a list of items in this menu.
  261. */
  262. public List<CustomMenuItem> getItems() {
  263. return items;
  264. }
  265. /**
  266. * Remove all the items in this menu.
  267. */
  268. public void clearItems() {
  269. for (CustomMenuItem child : items) {
  270. remove(child);
  271. }
  272. items.clear();
  273. }
  274. /**
  275. * Add a new item to this menu.
  276. *
  277. * @param html
  278. * items text
  279. * @param cmd
  280. * items command
  281. * @return the item created
  282. */
  283. public CustomMenuItem addItem(String html, Command cmd) {
  284. CustomMenuItem item = GWT.create(CustomMenuItem.class);
  285. item.setHTML(html);
  286. item.setCommand(cmd);
  287. addItem(item);
  288. return item;
  289. }
  290. /**
  291. * Add a new item to this menu.
  292. *
  293. * @param item
  294. */
  295. public void addItem(CustomMenuItem item) {
  296. if (items.contains(item)) {
  297. return;
  298. }
  299. add(item);
  300. item.setParentMenu(this);
  301. item.setSelected(false);
  302. items.add(item);
  303. }
  304. public void addItem(CustomMenuItem item, int index) {
  305. if (items.contains(item)) {
  306. return;
  307. }
  308. insert(item, index);
  309. item.setParentMenu(this);
  310. item.setSelected(false);
  311. items.add(index, item);
  312. }
  313. /**
  314. * Remove the given item from this menu.
  315. *
  316. * @param item
  317. */
  318. public void removeItem(CustomMenuItem item) {
  319. if (items.contains(item)) {
  320. int index = items.indexOf(item);
  321. remove(item);
  322. items.remove(index);
  323. }
  324. }
  325. /*
  326. * @see
  327. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user
  328. * .client.Event)
  329. */
  330. @Override
  331. public void onBrowserEvent(Event e) {
  332. super.onBrowserEvent(e);
  333. // Handle onload events (icon loaded, size changes)
  334. if (DOM.eventGetType(e) == Event.ONLOAD) {
  335. VMenuBar parent = getParentMenu();
  336. if (parent != null) {
  337. // The onload event for an image in a popup should be sent to
  338. // the parent, which owns the popup
  339. parent.iconLoaded();
  340. } else {
  341. // Onload events for images in the root menu are handled by the
  342. // root menu itself
  343. iconLoaded();
  344. }
  345. return;
  346. }
  347. Element targetElement = DOM.eventGetTarget(e);
  348. CustomMenuItem targetItem = null;
  349. for (int i = 0; i < items.size(); i++) {
  350. CustomMenuItem item = items.get(i);
  351. if (DOM.isOrHasChild(item.getElement(), targetElement)) {
  352. targetItem = item;
  353. }
  354. }
  355. if (targetItem != null) {
  356. switch (DOM.eventGetType(e)) {
  357. case Event.ONCLICK:
  358. if (isEnabled() && targetItem.isEnabled()) {
  359. itemClick(targetItem);
  360. }
  361. break;
  362. case Event.ONMOUSEOVER:
  363. LazyCloser.cancelClosing();
  364. if (isEnabled() && targetItem.isEnabled()) {
  365. itemOver(targetItem);
  366. }
  367. break;
  368. case Event.ONMOUSEOUT:
  369. itemOut(targetItem);
  370. LazyCloser.schedule();
  371. break;
  372. }
  373. }
  374. }
  375. private boolean isEnabled() {
  376. return enabled;
  377. }
  378. private void iconLoaded() {
  379. iconLoadedExecutioner.trigger();
  380. }
  381. /**
  382. * When an item is clicked.
  383. *
  384. * @param item
  385. */
  386. public void itemClick(CustomMenuItem item) {
  387. boolean triggered = triggerEventIfNeeded(item);
  388. if (item.getCommand() != null || triggered) {
  389. try {
  390. if (item.getCommand() != null) {
  391. item.getCommand().execute();
  392. }
  393. } finally {
  394. setSelected(null);
  395. if (visibleChildMenu != null) {
  396. visibleChildMenu.hideChildren();
  397. }
  398. hideParents(true);
  399. menuVisible = false;
  400. }
  401. } else {
  402. if (item.getSubMenu() != null
  403. && item.getSubMenu() != visibleChildMenu) {
  404. setSelected(item);
  405. showChildMenu(item);
  406. menuVisible = true;
  407. } else if (!subMenu) {
  408. setSelected(null);
  409. hideChildren();
  410. menuVisible = false;
  411. }
  412. }
  413. }
  414. /**
  415. * When the user hovers the mouse over the item.
  416. *
  417. * @param item
  418. */
  419. public void itemOver(CustomMenuItem item) {
  420. if ((openRootOnHover || subMenu || menuVisible)
  421. && !item.isSeparator()) {
  422. setSelected(item);
  423. if (!subMenu && openRootOnHover && !menuVisible) {
  424. menuVisible = true; // start opening menus
  425. LazyCloser.prepare(this);
  426. }
  427. }
  428. if (menuVisible && visibleChildMenu != item.getSubMenu()
  429. && popup != null) {
  430. // #15255 - disable animation-in/out when hide in this case
  431. popup.hide(false, false, false);
  432. }
  433. if (menuVisible && item.getSubMenu() != null
  434. && visibleChildMenu != item.getSubMenu()) {
  435. showChildMenu(item);
  436. }
  437. }
  438. /**
  439. * When the mouse is moved away from an item.
  440. *
  441. * @param item
  442. */
  443. public void itemOut(CustomMenuItem item) {
  444. if (visibleChildMenu != item.getSubMenu()) {
  445. hideChildMenu(item);
  446. setSelected(null);
  447. } else if (visibleChildMenu == null) {
  448. setSelected(null);
  449. }
  450. }
  451. /**
  452. * Used to autoclose submenus when they the menu is in a mode which opens
  453. * root menus on mouse hover.
  454. */
  455. private static class LazyCloser extends Timer {
  456. static LazyCloser instance;
  457. private VMenuBar activeRoot;
  458. @Override
  459. public void run() {
  460. activeRoot.hideChildren();
  461. activeRoot.setSelected(null);
  462. activeRoot.menuVisible = false;
  463. activeRoot = null;
  464. }
  465. public static void cancelClosing() {
  466. if (instance != null) {
  467. instance.cancel();
  468. }
  469. }
  470. public static void prepare(VMenuBar vMenuBar) {
  471. if (instance == null) {
  472. instance = new LazyCloser();
  473. }
  474. if (instance.activeRoot == vMenuBar) {
  475. instance.cancel();
  476. } else if (instance.activeRoot != null) {
  477. instance.cancel();
  478. instance.run();
  479. }
  480. instance.activeRoot = vMenuBar;
  481. }
  482. public static void schedule() {
  483. if (instance != null && instance.activeRoot != null) {
  484. instance.schedule(750);
  485. }
  486. }
  487. }
  488. /**
  489. * Shows the child menu of an item. The caller must ensure that the item has
  490. * a submenu.
  491. *
  492. * @param item
  493. */
  494. public void showChildMenu(CustomMenuItem item) {
  495. int left = 0;
  496. int top = 0;
  497. if (subMenu) {
  498. left = item.getParentMenu().getAbsoluteLeft()
  499. + item.getParentMenu().getOffsetWidth();
  500. top = item.getAbsoluteTop();
  501. } else {
  502. left = item.getAbsoluteLeft();
  503. top = item.getParentMenu().getAbsoluteTop()
  504. + item.getParentMenu().getOffsetHeight();
  505. }
  506. showChildMenuAt(item, top, left);
  507. }
  508. protected void showChildMenuAt(CustomMenuItem item, int top, int left) {
  509. final int shadowSpace = 10;
  510. popup = createOverlay();
  511. popup.setOwner(this);
  512. /*
  513. * Use parents primary style name if possible and remove the submenu
  514. * prefix if needed
  515. */
  516. String primaryStyleName = parentMenu != null
  517. ? parentMenu.getStylePrimaryName()
  518. : getStylePrimaryName();
  519. if (subMenu) {
  520. primaryStyleName = primaryStyleName
  521. .replace(SUBMENU_CLASSNAME_PREFIX, "");
  522. }
  523. popup.setStyleName(primaryStyleName + "-popup");
  524. // Setting owner and handlers to support tooltips. Needed for tooltip
  525. // handling of overlay widgets (will direct queries to parent menu)
  526. if (parentMenu == null) {
  527. popup.setOwner(this);
  528. } else {
  529. VMenuBar parent = parentMenu;
  530. popup.addAutoHidePartner(parent.getSelected().getElement());
  531. while (parent.getParentMenu() != null) {
  532. parent = parent.getParentMenu();
  533. popup.addAutoHidePartner(parent.getSelected().getElement());
  534. }
  535. popup.setOwner(parent);
  536. }
  537. if (client != null) {
  538. client.getVTooltip().connectHandlersToWidget(popup);
  539. }
  540. popup.setWidget(item.getSubMenu());
  541. popup.addCloseHandler(this);
  542. popup.addAutoHidePartner(item.getElement());
  543. popup.addDomHandler(this, MouseOutEvent.getType());
  544. popup.addDomHandler(this, MouseOverEvent.getType());
  545. // at 0,0 because otherwise IE7 add extra scrollbars (#5547)
  546. popup.setPopupPosition(0, 0);
  547. item.getSubMenu().onShow();
  548. visibleChildMenu = item.getSubMenu();
  549. item.getSubMenu().setParentMenu(this);
  550. popup.show();
  551. if (left + popup.getOffsetWidth() >= RootPanel.getBodyElement()
  552. .getOffsetWidth() - shadowSpace) {
  553. if (subMenu) {
  554. left = item.getParentMenu().getAbsoluteLeft()
  555. - popup.getOffsetWidth() - shadowSpace;
  556. } else {
  557. left = RootPanel.getBodyElement().getOffsetWidth()
  558. - popup.getOffsetWidth() - shadowSpace;
  559. }
  560. // Accommodate space for shadow
  561. if (left < shadowSpace) {
  562. left = shadowSpace;
  563. }
  564. }
  565. top = adjustPopupHeight(top, shadowSpace);
  566. popup.setPopupPosition(left, top);
  567. }
  568. /**
  569. * Create an overlay for the menu bar.
  570. *
  571. * This method can be overridden to use a custom overlay.
  572. *
  573. * @since 7.6
  574. * @return overlay to use
  575. */
  576. protected VOverlay createOverlay() {
  577. return new VOverlay(true, false);
  578. }
  579. private int adjustPopupHeight(int top, final int shadowSpace) {
  580. // Check that the popup will fit the screen
  581. int availableHeight = RootPanel.getBodyElement().getOffsetHeight() - top
  582. - shadowSpace;
  583. int missingHeight = popup.getOffsetHeight() - availableHeight;
  584. if (missingHeight > 0) {
  585. // First move the top of the popup to get more space
  586. // Don't move above top of screen, don't move more than needed
  587. int moveUpBy = Math.min(top - shadowSpace, missingHeight);
  588. // Update state
  589. top -= moveUpBy;
  590. missingHeight -= moveUpBy;
  591. availableHeight += moveUpBy;
  592. if (missingHeight > 0) {
  593. int contentWidth = visibleChildMenu.getOffsetWidth();
  594. // If there's still not enough room, limit height to fit and add
  595. // a scroll bar
  596. Style style = popup.getElement().getStyle();
  597. style.setHeight(availableHeight, Unit.PX);
  598. style.setOverflowY(Overflow.SCROLL);
  599. // Make room for the scroll bar by adjusting the width of the
  600. // popup
  601. style.setWidth(
  602. contentWidth + WidgetUtil.getNativeScrollbarSize(),
  603. Unit.PX);
  604. popup.positionOrSizeUpdated();
  605. }
  606. }
  607. return top;
  608. }
  609. /**
  610. * Hides the submenu of an item.
  611. *
  612. * @param item
  613. */
  614. public void hideChildMenu(CustomMenuItem item) {
  615. if (visibleChildMenu != null && visibleChildMenu != item.getSubMenu()) {
  616. popup.hide();
  617. }
  618. }
  619. /**
  620. * When the menu is shown.
  621. */
  622. public void onShow() {
  623. // remove possible previous selection
  624. if (selected != null) {
  625. selected.setSelected(false);
  626. selected = null;
  627. }
  628. menuVisible = true;
  629. }
  630. /**
  631. * Listener method, fired when this menu is closed.
  632. */
  633. @Override
  634. public void onClose(CloseEvent<PopupPanel> event) {
  635. close(event, true);
  636. }
  637. protected void close(CloseEvent<PopupPanel> event, boolean animated) {
  638. hideChildren(animated, animated);
  639. if (event.isAutoClosed()) {
  640. hideParents(true, animated);
  641. menuVisible = false;
  642. }
  643. visibleChildMenu = null;
  644. popup = null;
  645. }
  646. /**
  647. * Recursively hide all child menus.
  648. */
  649. public void hideChildren() {
  650. hideChildren(true, true);
  651. }
  652. /**
  653. *
  654. * Recursively hide all child menus.
  655. *
  656. * @param animateIn
  657. * enable/disable animate-in animation when hide popup
  658. * @param animateOut
  659. * enable/disable animate-out animation when hide popup
  660. * @since 7.3.7
  661. */
  662. public void hideChildren(boolean animateIn, boolean animateOut) {
  663. if (visibleChildMenu != null) {
  664. visibleChildMenu.menuVisible = false;
  665. visibleChildMenu.hideChildren(animateIn, animateOut);
  666. popup.hide(false, animateIn, animateOut);
  667. }
  668. }
  669. /**
  670. * Recursively hide all parent menus.
  671. */
  672. public void hideParents(boolean autoClosed) {
  673. hideParents(autoClosed, true);
  674. }
  675. public void hideParents(boolean autoClosed, boolean animated) {
  676. if (visibleChildMenu != null) {
  677. popup.hide(false, animated, animated);
  678. setSelected(null);
  679. menuVisible = false;
  680. }
  681. if (getParentMenu() != null) {
  682. getParentMenu().hideParents(autoClosed, animated);
  683. }
  684. }
  685. /**
  686. * Returns the parent menu of this menu, or null if this is the top-level
  687. * menu.
  688. *
  689. * @return
  690. */
  691. public VMenuBar getParentMenu() {
  692. return parentMenu;
  693. }
  694. /**
  695. * Set the parent menu of this menu.
  696. *
  697. * @param parent
  698. */
  699. public void setParentMenu(VMenuBar parent) {
  700. parentMenu = parent;
  701. }
  702. /**
  703. * Returns the currently selected item of this menu, or null if nothing is
  704. * selected.
  705. *
  706. * @return
  707. */
  708. public CustomMenuItem getSelected() {
  709. return selected;
  710. }
  711. /**
  712. * Set the currently selected item of this menu.
  713. *
  714. * @param item
  715. */
  716. public void setSelected(CustomMenuItem item) {
  717. // If we had something selected, unselect
  718. if (item != selected && selected != null) {
  719. selected.setSelected(false);
  720. }
  721. // If we have a valid selection, select it
  722. if (item != null) {
  723. item.setSelected(true);
  724. }
  725. selected = item;
  726. }
  727. /**
  728. *
  729. * A class to hold information on menu items.
  730. *
  731. */
  732. public static class CustomMenuItem extends Widget
  733. implements HasHTML, SubPartAware {
  734. protected String html = null;
  735. protected Command command = null;
  736. protected VMenuBar subMenu = null;
  737. protected VMenuBar parentMenu = null;
  738. protected boolean enabled = true;
  739. protected boolean isSeparator = false;
  740. protected boolean checkable = false;
  741. protected boolean checked = false;
  742. protected boolean selected = false;
  743. protected String description = null;
  744. protected ContentMode descriptionContentMode = null;
  745. private String styleName;
  746. private String id;
  747. /**
  748. * Default menu item {@link Widget} constructor for GWT.create().
  749. *
  750. * Use {@link #setHTML(String)} and {@link #setCommand(Command)} after
  751. * constructing a menu item.
  752. */
  753. public CustomMenuItem() {
  754. this("", null);
  755. }
  756. /**
  757. * Creates a menu item {@link Widget}.
  758. *
  759. * @param html
  760. * @param cmd
  761. * @deprecated use the default constructor and {@link #setHTML(String)}
  762. * and {@link #setCommand(Command)} instead
  763. */
  764. @Deprecated
  765. public CustomMenuItem(String html, Command cmd) {
  766. // We need spans to allow inline-block in IE
  767. setElement(DOM.createSpan());
  768. setHTML(html);
  769. setCommand(cmd);
  770. setSelected(false);
  771. }
  772. @Override
  773. public void onBrowserEvent(Event event) {
  774. VMenuBar p = getParentMenu();
  775. if (event.getTypeInt() == Event.ONKEYDOWN
  776. || event.getTypeInt() == Event.ONKEYPRESS) {
  777. if (p.getParentMenu() != null
  778. && p.getParentMenu().visibleChildMenu != null) {
  779. int keyCode = event.getKeyCode();
  780. if (keyCode == 0) {
  781. keyCode = event.getCharCode();
  782. }
  783. if (getParentMenu().handleNavigation(keyCode,
  784. event.getCtrlKey() || event.getMetaKey(),
  785. event.getShiftKey())) {
  786. event.preventDefault();
  787. }
  788. }
  789. }
  790. }
  791. @Override
  792. protected void onLoad() {
  793. super.onLoad();
  794. if (getParentMenu() != null
  795. && getParentMenu().getParentMenu() == null
  796. && getParentMenu().getItems().get(0).equals(this)) {
  797. getElement().setAttribute("tabindex", "0");
  798. } else {
  799. getElement().setAttribute("tabindex", "-1");
  800. }
  801. sinkEvents(Event.KEYEVENTS);
  802. }
  803. @Override
  804. public void setStyleName(String style) {
  805. super.setStyleName(style);
  806. updateStyleNames();
  807. // Pass stylename down to submenus
  808. if (getSubMenu() != null) {
  809. getSubMenu().setStyleName(style);
  810. }
  811. }
  812. public void setSelected(boolean selected) {
  813. this.selected = selected;
  814. updateStyleNames();
  815. if (selected) {
  816. getElement().focus();
  817. }
  818. }
  819. public void setChecked(boolean checked) {
  820. if (checkable && !isSeparator) {
  821. this.checked = checked;
  822. } else {
  823. this.checked = false;
  824. }
  825. updateStyleNames();
  826. }
  827. public boolean isChecked() {
  828. return checked;
  829. }
  830. public void setCheckable(boolean checkable) {
  831. if (checkable && !isSeparator) {
  832. this.checkable = true;
  833. } else {
  834. setChecked(false);
  835. this.checkable = false;
  836. }
  837. }
  838. public boolean isCheckable() {
  839. return checkable;
  840. }
  841. /*
  842. * setters and getters for the fields
  843. */
  844. public void setSubMenu(VMenuBar subMenu) {
  845. this.subMenu = subMenu;
  846. if (subMenu != null) {
  847. getElement().setAttribute("aria-haspopup", "true");
  848. } else {
  849. getElement().setAttribute("aria-haspopup", "false");
  850. }
  851. }
  852. public VMenuBar getSubMenu() {
  853. return subMenu;
  854. }
  855. public void setParentMenu(VMenuBar parentMenu) {
  856. this.parentMenu = parentMenu;
  857. updateStyleNames();
  858. }
  859. public void updateStyleNames() {
  860. if (parentMenu == null) {
  861. // Style names depend on the parent menu's primary style name so
  862. // don't do updates until the item has a parent
  863. return;
  864. }
  865. String primaryStyleName = parentMenu.getStylePrimaryName();
  866. if (parentMenu.subMenu) {
  867. primaryStyleName = primaryStyleName
  868. .replace(SUBMENU_CLASSNAME_PREFIX, "");
  869. }
  870. String currentStyles = super.getStyleName();
  871. List<String> customStyles = new ArrayList<>();
  872. for (String style : currentStyles.split(" ")) {
  873. if (!style.isEmpty() && !style.startsWith(primaryStyleName)) {
  874. customStyles.add(style);
  875. }
  876. }
  877. refreshPrimaryStyleNameAndAriaAttributes(primaryStyleName);
  878. for (String customStyle : customStyles) {
  879. super.addStyleName(customStyle);
  880. }
  881. if (styleName != null) {
  882. addStyleDependentName(styleName);
  883. addStyleName(styleName);
  884. }
  885. if (enabled) {
  886. removeStyleDependentName("disabled");
  887. } else {
  888. addStyleDependentName("disabled");
  889. }
  890. if (selected && isSelectable()) {
  891. addStyleDependentName("selected");
  892. // needed for IE6 to have a single style name to match for an
  893. // element
  894. // TODO Can be optimized now that IE6 is not supported any more
  895. if (checkable) {
  896. if (checked) {
  897. removeStyleDependentName("selected-unchecked");
  898. addStyleDependentName("selected-checked");
  899. } else {
  900. removeStyleDependentName("selected-checked");
  901. addStyleDependentName("selected-unchecked");
  902. }
  903. }
  904. } else {
  905. removeStyleDependentName("selected");
  906. // needed for IE6 to have a single style name to match for an
  907. // element
  908. removeStyleDependentName("selected-checked");
  909. removeStyleDependentName("selected-unchecked");
  910. }
  911. if (checkable && !isSeparator) {
  912. if (checked) {
  913. addStyleDependentName("checked");
  914. removeStyleDependentName("unchecked");
  915. } else {
  916. addStyleDependentName("unchecked");
  917. removeStyleDependentName("checked");
  918. }
  919. }
  920. }
  921. private void refreshPrimaryStyleNameAndAriaAttributes(
  922. String primaryStyleName) {
  923. if (isSeparator) {
  924. super.setStyleName(primaryStyleName + "-separator");
  925. getElement().setAttribute("role", "separator");
  926. } else {
  927. super.setStyleName(primaryStyleName + "-menuitem");
  928. if (isCheckable()) {
  929. getElement().setAttribute("role", "menuitemcheckbox");
  930. getElement().setAttribute("aria-checked",
  931. String.valueOf(isChecked()));
  932. } else {
  933. getElement().setAttribute("role", "menuitem");
  934. }
  935. if (isEnabled()) {
  936. getElement().removeAttribute("aria-disabled");
  937. } else {
  938. getElement().setAttribute("aria-disabled", "true");
  939. }
  940. }
  941. }
  942. public VMenuBar getParentMenu() {
  943. return parentMenu;
  944. }
  945. public void setCommand(Command command) {
  946. this.command = command;
  947. }
  948. public Command getCommand() {
  949. return command;
  950. }
  951. @Override
  952. public String getHTML() {
  953. return html;
  954. }
  955. @Override
  956. public void setHTML(String html) {
  957. this.html = html;
  958. DOM.setInnerHTML(getElement(), html);
  959. // Sink the onload event for any icons. The onload
  960. // events are handled by the parent VMenuBar.
  961. WidgetUtil.sinkOnloadForImages(getElement());
  962. }
  963. @Override
  964. public String getText() {
  965. return html;
  966. }
  967. @Override
  968. public void setText(String text) {
  969. setHTML(WidgetUtil.escapeHTML(text));
  970. }
  971. public void setEnabled(boolean enabled) {
  972. this.enabled = enabled;
  973. updateStyleNames();
  974. }
  975. public boolean isEnabled() {
  976. return enabled;
  977. }
  978. public void setSeparator(boolean separator) {
  979. isSeparator = separator;
  980. updateStyleNames();
  981. if (!separator) {
  982. setEnabled(enabled);
  983. }
  984. }
  985. public boolean isSeparator() {
  986. return isSeparator;
  987. }
  988. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  989. setSeparator(uidl.hasAttribute("separator"));
  990. setEnabled(!uidl
  991. .hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_DISABLED));
  992. if (!isSeparator()
  993. && uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_CHECKED)) {
  994. // if the selected attribute is present (either true or false),
  995. // the item is selectable
  996. setCheckable(true);
  997. setChecked(uidl.getBooleanAttribute(
  998. MenuBarConstants.ATTRIBUTE_CHECKED));
  999. } else {
  1000. setCheckable(false);
  1001. }
  1002. if (uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_STYLE)) {
  1003. styleName = uidl.getStringAttribute(
  1004. MenuBarConstants.ATTRIBUTE_ITEM_STYLE);
  1005. }
  1006. if (uidl.hasAttribute(
  1007. MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION)) {
  1008. description = uidl.getStringAttribute(
  1009. MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION);
  1010. }
  1011. if (uidl.hasAttribute(
  1012. MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION_CONTENT_MODE)) {
  1013. String contentModeString = uidl.getStringAttribute(
  1014. MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION_CONTENT_MODE);
  1015. descriptionContentMode = ContentMode.valueOf(contentModeString);
  1016. } else {
  1017. descriptionContentMode = ContentMode.PREFORMATTED;
  1018. }
  1019. updateStyleNames();
  1020. }
  1021. public TooltipInfo getTooltip() {
  1022. if (description == null || descriptionContentMode == null) {
  1023. return null;
  1024. }
  1025. return new TooltipInfo(description, descriptionContentMode, null,
  1026. this);
  1027. }
  1028. /**
  1029. * Checks if the item can be selected.
  1030. *
  1031. * @return true if it is possible to select this item, false otherwise
  1032. */
  1033. public boolean isSelectable() {
  1034. return !isSeparator();
  1035. }
  1036. @SuppressWarnings("deprecation")
  1037. @Override
  1038. public com.google.gwt.user.client.Element getSubPartElement(
  1039. String subPart) {
  1040. if (getSubMenu() != null && getSubMenu().menuVisible) {
  1041. return getSubMenu().getSubPartElement(subPart);
  1042. }
  1043. return null;
  1044. }
  1045. @SuppressWarnings("deprecation")
  1046. @Override
  1047. public String getSubPartName(
  1048. com.google.gwt.user.client.Element subElement) {
  1049. if (getSubMenu() != null && getSubMenu().menuVisible) {
  1050. return getSubMenu().getSubPartName(subElement);
  1051. }
  1052. return null;
  1053. }
  1054. public String getId() {
  1055. return id;
  1056. }
  1057. public void setId(String id) {
  1058. this.id = id;
  1059. }
  1060. public void setDescription(String description) {
  1061. this.description = description;
  1062. }
  1063. public void setDescriptionContentMode(
  1064. ContentMode descriptionContentMode) {
  1065. this.descriptionContentMode = descriptionContentMode;
  1066. }
  1067. }
  1068. /**
  1069. * @author Jouni Koivuviita / Vaadin Ltd.
  1070. */
  1071. public void iLayout() {
  1072. iLayout(false);
  1073. updateSize();
  1074. }
  1075. public void iLayout(boolean iconLoadEvent) {
  1076. // Only collapse if there is more than one item in the root menu and the
  1077. // menu has an explicit size
  1078. if ((getItems().size() > 1 || (collapsedRootItems != null
  1079. && !collapsedRootItems.getItems().isEmpty()))
  1080. && getElement().getStyle().getProperty("width") != null
  1081. && moreItem != null) {
  1082. // Measure the width of the "more" item
  1083. final boolean morePresent = getItems().contains(moreItem);
  1084. addItem(moreItem);
  1085. final int moreItemWidth = moreItem.getOffsetWidth();
  1086. if (!morePresent) {
  1087. removeItem(moreItem);
  1088. }
  1089. int availableWidth = LayoutManager.get(client)
  1090. .getInnerWidth(getElement());
  1091. // Used width includes the "more" item if present
  1092. int usedWidth = getConsumedWidth();
  1093. int diff = availableWidth - usedWidth;
  1094. removeItem(moreItem);
  1095. if (diff < 0) {
  1096. // Too many items: collapse last items from root menu
  1097. int widthNeeded = usedWidth - availableWidth;
  1098. if (!morePresent) {
  1099. widthNeeded += moreItemWidth;
  1100. }
  1101. int widthReduced = 0;
  1102. while (widthReduced < widthNeeded && !getItems().isEmpty()) {
  1103. // Move last root menu item to collapsed menu
  1104. CustomMenuItem collapse = getItems()
  1105. .get(getItems().size() - 1);
  1106. widthReduced += collapse.getOffsetWidth();
  1107. removeItem(collapse);
  1108. collapsedRootItems.addItem(collapse, 0);
  1109. }
  1110. } else if (!collapsedRootItems.getItems().isEmpty()) {
  1111. // Space available for items: expand first items from collapsed
  1112. // menu
  1113. int widthAvailable = diff + moreItemWidth;
  1114. int widthGrowth = 0;
  1115. while (widthAvailable > widthGrowth
  1116. && !collapsedRootItems.getItems().isEmpty()) {
  1117. // Move first item from collapsed menu to the root menu
  1118. CustomMenuItem expand = collapsedRootItems.getItems()
  1119. .get(0);
  1120. collapsedRootItems.removeItem(expand);
  1121. addItem(expand);
  1122. widthGrowth += expand.getOffsetWidth();
  1123. if (!collapsedRootItems.getItems().isEmpty()) {
  1124. widthAvailable -= moreItemWidth;
  1125. }
  1126. if (widthGrowth > widthAvailable) {
  1127. removeItem(expand);
  1128. collapsedRootItems.addItem(expand, 0);
  1129. } else {
  1130. widthAvailable = diff + moreItemWidth;
  1131. }
  1132. }
  1133. }
  1134. if (!collapsedRootItems.getItems().isEmpty()) {
  1135. addItem(moreItem);
  1136. }
  1137. }
  1138. // If a popup is open we might need to adjust the shadow as well if an
  1139. // icon shown in that popup was loaded
  1140. if (popup != null) {
  1141. // Forces a recalculation of the shadow size
  1142. popup.show();
  1143. }
  1144. if (iconLoadEvent) {
  1145. // Size have changed if the width is undefined
  1146. Util.notifyParentOfSizeChange(this, false);
  1147. }
  1148. }
  1149. private int getConsumedWidth() {
  1150. int w = 0;
  1151. for (CustomMenuItem item : getItems()) {
  1152. if (!collapsedRootItems.getItems().contains(item)) {
  1153. w += item.getOffsetWidth();
  1154. }
  1155. }
  1156. return w;
  1157. }
  1158. /*
  1159. * (non-Javadoc)
  1160. *
  1161. * @see
  1162. * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
  1163. * .gwt.event.dom.client.KeyPressEvent)
  1164. */
  1165. @Override
  1166. public void onKeyPress(KeyPressEvent event) {
  1167. // A bug fix for #14041
  1168. // getKeyCode and getCharCode return different values for different
  1169. // browsers
  1170. int keyCode = event.getNativeEvent().getKeyCode();
  1171. if (keyCode == 0) {
  1172. keyCode = event.getNativeEvent().getCharCode();
  1173. }
  1174. if (handleNavigation(keyCode,
  1175. event.isControlKeyDown() || event.isMetaKeyDown(),
  1176. event.isShiftKeyDown())) {
  1177. event.preventDefault();
  1178. }
  1179. }
  1180. /*
  1181. * (non-Javadoc)
  1182. *
  1183. * @see
  1184. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1185. * .event.dom.client.KeyDownEvent)
  1186. */
  1187. @Override
  1188. public void onKeyDown(KeyDownEvent event) {
  1189. // A bug fix for #14041
  1190. // getKeyCode and getCharCode return different values for different
  1191. // browsers
  1192. int keyCode = event.getNativeEvent().getKeyCode();
  1193. if (keyCode == 0) {
  1194. keyCode = event.getNativeEvent().getCharCode();
  1195. }
  1196. if (handleNavigation(keyCode,
  1197. event.isControlKeyDown() || event.isMetaKeyDown(),
  1198. event.isShiftKeyDown())) {
  1199. event.preventDefault();
  1200. }
  1201. }
  1202. /**
  1203. * Get the key that moves the selection upwards. By default it is the up
  1204. * arrow key but by overriding this you can change the key to whatever you
  1205. * want.
  1206. *
  1207. * @return The keycode of the key
  1208. */
  1209. protected int getNavigationUpKey() {
  1210. return KeyCodes.KEY_UP;
  1211. }
  1212. /**
  1213. * Get the key that moves the selection downwards. By default it is the down
  1214. * arrow key but by overriding this you can change the key to whatever you
  1215. * want.
  1216. *
  1217. * @return The keycode of the key
  1218. */
  1219. protected int getNavigationDownKey() {
  1220. return KeyCodes.KEY_DOWN;
  1221. }
  1222. /**
  1223. * Get the key that moves the selection left. By default it is the left
  1224. * arrow key but by overriding this you can change the key to whatever you
  1225. * want.
  1226. *
  1227. * @return The keycode of the key
  1228. */
  1229. protected int getNavigationLeftKey() {
  1230. return KeyCodes.KEY_LEFT;
  1231. }
  1232. /**
  1233. * Get the key that moves the selection right. By default it is the right
  1234. * arrow key but by overriding this you can change the key to whatever you
  1235. * want.
  1236. *
  1237. * @return The keycode of the key
  1238. */
  1239. protected int getNavigationRightKey() {
  1240. return KeyCodes.KEY_RIGHT;
  1241. }
  1242. /**
  1243. * Get the key that selects a menu item. By default it is the Enter key but
  1244. * by overriding this you can change the key to whatever you want.
  1245. *
  1246. * @deprecated use {@link #isNavigationSelectKey(int)} instead
  1247. * @return
  1248. */
  1249. @Deprecated
  1250. protected int getNavigationSelectKey() {
  1251. return KeyCodes.KEY_ENTER;
  1252. }
  1253. /**
  1254. * Checks whether key code selects a menu item. By default it is the Enter
  1255. * and Space keys but by overriding this you can change the keys to whatever
  1256. * you want.
  1257. *
  1258. * @since 7.2
  1259. * @param keycode
  1260. * @return true if key selects menu item
  1261. */
  1262. protected boolean isNavigationSelectKey(int keycode) {
  1263. return keycode == getNavigationSelectKey()
  1264. || keycode == KeyCodes.KEY_SPACE;
  1265. }
  1266. /**
  1267. * Get the key that closes the menu. By default it is the escape key but by
  1268. * overriding this yoy can change the key to whatever you want.
  1269. *
  1270. * @return
  1271. */
  1272. protected int getCloseMenuKey() {
  1273. return KeyCodes.KEY_ESCAPE;
  1274. }
  1275. /**
  1276. * Handles the keyboard events handled by the MenuBar.
  1277. *
  1278. * @param keycode
  1279. * The key code received
  1280. * @param ctrl
  1281. * Whether {@code CTRL} was pressed
  1282. * @param shift
  1283. * Whether {@code SHIFT} was pressed
  1284. * @return true if the navigation event was handled
  1285. */
  1286. public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  1287. // If tab or shift+tab close menus
  1288. if (keycode == KeyCodes.KEY_TAB) {
  1289. setSelected(null);
  1290. hideParents(false);
  1291. menuVisible = false;
  1292. VMenuBar root = getParentMenu();
  1293. while (root != null && root.getParentMenu() != null) {
  1294. root = root.getParentMenu();
  1295. }
  1296. if (root != null) {
  1297. if (shift) {
  1298. root.ignoreFocus = true;
  1299. root.getElement().focus();
  1300. root.ignoreFocus = false;
  1301. } else {
  1302. root.getElement().focus();
  1303. root.setSelected(null);
  1304. }
  1305. } else if (shift) {
  1306. ignoreFocus = true;
  1307. getElement().focus();
  1308. ignoreFocus = false;
  1309. }
  1310. return false;
  1311. }
  1312. if (ctrl || shift || !isEnabled()) {
  1313. // Do not handle tab key, nor ctrl keys
  1314. return false;
  1315. }
  1316. if (keycode == getNavigationLeftKey()) {
  1317. if (getSelected() == null) {
  1318. // If nothing is selected then select the last item
  1319. setSelected(items.get(items.size() - 1));
  1320. if (!getSelected().isSelectable()) {
  1321. handleNavigation(keycode, ctrl, shift);
  1322. }
  1323. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1324. // If this is the root menu then move to the left
  1325. int idx = items.indexOf(getSelected());
  1326. if (idx > 0) {
  1327. setSelected(items.get(idx - 1));
  1328. } else {
  1329. setSelected(items.get(items.size() - 1));
  1330. }
  1331. if (!getSelected().isSelectable()) {
  1332. handleNavigation(keycode, ctrl, shift);
  1333. }
  1334. } else if (visibleChildMenu != null) {
  1335. // Redirect all navigation to the submenu
  1336. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1337. } else if (getParentMenu().getParentMenu() == null) {
  1338. // Inside a sub menu, whose parent is a root menu item
  1339. VMenuBar root = getParentMenu();
  1340. root.getSelected().getSubMenu().setSelected(null);
  1341. // #15255 - disable animate-in/out when hide popup
  1342. root.hideChildren(false, false);
  1343. // Get the root menus items and select the previous one
  1344. int idx = root.getItems().indexOf(root.getSelected());
  1345. idx = idx > 0 ? idx : root.getItems().size();
  1346. CustomMenuItem selected = root.getItems().get(--idx);
  1347. while (selected.isSeparator() || !selected.isEnabled()) {
  1348. idx = idx > 0 ? idx : root.getItems().size();
  1349. selected = root.getItems().get(--idx);
  1350. }
  1351. root.setSelected(selected);
  1352. openMenuAndFocusFirstIfPossible(selected);
  1353. } else {
  1354. getParentMenu().getSelected().getSubMenu().setSelected(null);
  1355. getParentMenu().hideChildren();
  1356. getParentMenu().getSelected().getElement().focus();
  1357. getParentMenu().menuVisible = false;
  1358. }
  1359. return true;
  1360. } else if (keycode == getNavigationRightKey()) {
  1361. if (getSelected() == null) {
  1362. // If nothing is selected then select the first item
  1363. setSelected(items.get(0));
  1364. if (!getSelected().isSelectable()) {
  1365. handleNavigation(keycode, ctrl, shift);
  1366. }
  1367. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1368. // If this is the root menu then move to the right
  1369. int idx = items.indexOf(getSelected());
  1370. if (idx < items.size() - 1) {
  1371. setSelected(items.get(idx + 1));
  1372. } else {
  1373. setSelected(items.get(0));
  1374. }
  1375. if (!getSelected().isSelectable()) {
  1376. handleNavigation(keycode, ctrl, shift);
  1377. }
  1378. } else if (visibleChildMenu == null
  1379. && getSelected().getSubMenu() != null) {
  1380. // If the item has a submenu then show it and move the selection
  1381. // there
  1382. showChildMenu(getSelected());
  1383. menuVisible = true;
  1384. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1385. } else if (visibleChildMenu == null) {
  1386. // Get the root menu
  1387. VMenuBar root = getParentMenu();
  1388. while (root.getParentMenu() != null) {
  1389. root = root.getParentMenu();
  1390. }
  1391. // Hide the submenu (#15255 - disable animate-in/out when hide
  1392. // popup)
  1393. root.hideChildren(false, false);
  1394. // Get the root menus items and select the next one
  1395. int idx = root.getItems().indexOf(root.getSelected());
  1396. idx = idx < root.getItems().size() - 1 ? idx : -1;
  1397. CustomMenuItem selected = root.getItems().get(++idx);
  1398. while (selected.isSeparator() || !selected.isEnabled()) {
  1399. idx = idx < root.getItems().size() - 1 ? idx : -1;
  1400. selected = root.getItems().get(++idx);
  1401. }
  1402. root.setSelected(selected);
  1403. openMenuAndFocusFirstIfPossible(selected);
  1404. } else if (visibleChildMenu != null) {
  1405. // Redirect all navigation to the submenu
  1406. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1407. }
  1408. return true;
  1409. } else if (keycode == getNavigationUpKey()) {
  1410. if (getSelected() == null) {
  1411. // If nothing is selected then select the last item
  1412. setSelected(items.get(items.size() - 1));
  1413. if (!getSelected().isSelectable()) {
  1414. handleNavigation(keycode, ctrl, shift);
  1415. }
  1416. } else if (visibleChildMenu != null) {
  1417. // Redirect all navigation to the submenu
  1418. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1419. } else {
  1420. // Select the previous item if possible or loop to the last
  1421. // item. If menu is in the first popup (opens down), closes the
  1422. // popup. If menu is the root menu, opens the popup.
  1423. int idx = items.indexOf(getSelected());
  1424. if (getParentMenu() == null && visibleChildMenu == null) {
  1425. openMenuAndFocusLastIfPossible(selected);
  1426. } else if (idx > 0) {
  1427. setSelected(items.get(idx - 1));
  1428. } else if (getParentMenu() != null
  1429. && getParentMenu().getParentMenu() == null) {
  1430. getParentMenu().getSelected().getSubMenu()
  1431. .setSelected(null);
  1432. getParentMenu().hideChildren();
  1433. getParentMenu().getSelected().getElement().focus();
  1434. getParentMenu().menuVisible = false;
  1435. return true;
  1436. } else {
  1437. setSelected(items.get(items.size() - 1));
  1438. }
  1439. if (!getSelected().isSelectable()) {
  1440. handleNavigation(keycode, ctrl, shift);
  1441. }
  1442. }
  1443. return true;
  1444. } else if (keycode == getNavigationDownKey()) {
  1445. if (getSelected() == null) {
  1446. // If nothing is selected then select the first item
  1447. selectFirstItem();
  1448. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1449. // If this is the root menu the show the child menu with arrow
  1450. // down, if there is a child menu
  1451. openMenuAndFocusFirstIfPossible(getSelected());
  1452. } else if (visibleChildMenu != null) {
  1453. // Redirect all navigation to the submenu
  1454. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1455. } else {
  1456. // Select the next item if possible or loop to the first item
  1457. int idx = items.indexOf(getSelected());
  1458. if (idx < items.size() - 1) {
  1459. setSelected(items.get(idx + 1));
  1460. } else {
  1461. setSelected(items.get(0));
  1462. }
  1463. if (!getSelected().isSelectable()) {
  1464. handleNavigation(keycode, ctrl, shift);
  1465. }
  1466. }
  1467. return true;
  1468. } else if (keycode == getCloseMenuKey()) {
  1469. setSelected(null);
  1470. hideChildren();
  1471. if (getParentMenu() != null) {
  1472. getParentMenu().hideChildren();
  1473. getParentMenu().getSelected().getElement().focus();
  1474. }
  1475. menuVisible = false;
  1476. return true;
  1477. } else if (isNavigationSelectKey(keycode)) {
  1478. if (getSelected() == null) {
  1479. // If nothing is selected then select the first item
  1480. selectFirstItem();
  1481. } else if (!getSelected().isEnabled()) {
  1482. // NOP
  1483. } else if (visibleChildMenu != null) {
  1484. // Redirect all navigation to the submenu
  1485. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1486. menuVisible = false;
  1487. } else if (visibleChildMenu == null
  1488. && getSelected().getSubMenu() != null) {
  1489. // If the item has a sub menu then show it and move the
  1490. // selection there
  1491. openMenuAndFocusFirstIfPossible(getSelected());
  1492. } else {
  1493. try {
  1494. triggerEventIfNeeded(getSelected());
  1495. final Command command = getSelected().getCommand();
  1496. if (command != null) {
  1497. command.execute();
  1498. }
  1499. } finally {
  1500. setSelected(null);
  1501. hideParents(true);
  1502. // #17076 keyboard selected menuitem without children: do
  1503. // not leave menu to visible ("hover open") mode
  1504. menuVisible = false;
  1505. VMenuBar root = getRoot();
  1506. root.ignoreFocus = true;
  1507. root.getElement().focus();
  1508. root.ignoreFocus = false;
  1509. }
  1510. }
  1511. return true;
  1512. }
  1513. return false;
  1514. }
  1515. private boolean triggerEventIfNeeded(CustomMenuItem item) {
  1516. List<Command> commands = getTriggers().get(item.getId());
  1517. if (commands != null) {
  1518. for (Command command : commands) {
  1519. command.execute();
  1520. }
  1521. return true;
  1522. }
  1523. return false;
  1524. }
  1525. private void selectFirstItem() {
  1526. for (int i = 0; i < items.size(); i++) {
  1527. CustomMenuItem item = items.get(i);
  1528. if (item.isSelectable()) {
  1529. setSelected(item);
  1530. break;
  1531. }
  1532. }
  1533. }
  1534. private void selectLastItem() {
  1535. for (int i = items.size() - 1; i >= 0; i--) {
  1536. CustomMenuItem item = items.get(i);
  1537. if (item.isSelectable()) {
  1538. setSelected(item);
  1539. break;
  1540. }
  1541. }
  1542. }
  1543. private void openMenuAndFocusFirstIfPossible(CustomMenuItem menuItem) {
  1544. VMenuBar subMenu = menuItem.getSubMenu();
  1545. if (!menuItem.isEnabled() || subMenu == null) {
  1546. // No child menu or disabled? Nothing to do
  1547. return;
  1548. }
  1549. VMenuBar parentMenu = menuItem.getParentMenu();
  1550. parentMenu.showChildMenu(menuItem);
  1551. menuVisible = true;
  1552. // Select the first item in the newly open submenu
  1553. subMenu.selectFirstItem();
  1554. }
  1555. private void openMenuAndFocusLastIfPossible(CustomMenuItem menuItem) {
  1556. VMenuBar subMenu = menuItem.getSubMenu();
  1557. if (!menuItem.isEnabled() || subMenu == null) {
  1558. // No child menu or disabled? Nothing to do
  1559. return;
  1560. }
  1561. VMenuBar parentMenu = menuItem.getParentMenu();
  1562. parentMenu.showChildMenu(menuItem);
  1563. menuVisible = true;
  1564. // Select the last item in the newly open submenu
  1565. subMenu.selectLastItem();
  1566. }
  1567. /*
  1568. * (non-Javadoc)
  1569. *
  1570. * @see
  1571. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1572. * .dom.client.FocusEvent)
  1573. */
  1574. @Override
  1575. public void onFocus(FocusEvent event) {
  1576. if (!ignoreFocus && getSelected() == null) {
  1577. selectFirstItem();
  1578. }
  1579. }
  1580. private static final String SUBPART_PREFIX = "item";
  1581. @Override
  1582. public com.google.gwt.user.client.Element getSubPartElement(
  1583. String subPart) {
  1584. if (subPart.startsWith(SUBPART_PREFIX)) {
  1585. int index = Integer
  1586. .parseInt(subPart.substring(SUBPART_PREFIX.length()));
  1587. CustomMenuItem item = getItems().get(index);
  1588. return item.getElement();
  1589. } else {
  1590. Queue<CustomMenuItem> submenuItems = new LinkedList<>();
  1591. for (CustomMenuItem item : getItems()) {
  1592. if (isItemNamed(item, subPart)) {
  1593. return item.getElement();
  1594. }
  1595. if (item.getSubMenu() != null) {
  1596. submenuItems.addAll(item.getSubMenu().getItems());
  1597. }
  1598. }
  1599. while (!submenuItems.isEmpty()) {
  1600. CustomMenuItem item = submenuItems.poll();
  1601. if (!item.isSeparator() && isItemNamed(item, subPart)) {
  1602. return item.getElement();
  1603. }
  1604. if (item.getSubMenu() != null
  1605. && item.getSubMenu().menuVisible) {
  1606. submenuItems.addAll(item.getSubMenu().getItems());
  1607. }
  1608. }
  1609. return null;
  1610. }
  1611. }
  1612. private boolean isItemNamed(CustomMenuItem item, String name) {
  1613. Element lastChildElement = getLastChildElement(item);
  1614. if (getText(lastChildElement).equals(name)) {
  1615. return true;
  1616. }
  1617. return false;
  1618. }
  1619. /*
  1620. * Returns the text content of element without including the text of
  1621. * possible nested elements. It is assumed that the last child of element
  1622. * contains the text of interest and that the last child does not itself
  1623. * have children with text content. This method is used by
  1624. * getSubPartElement(String) so that possible text icons are not included in
  1625. * the textual matching (#14879).
  1626. */
  1627. private native String getText(Element element)
  1628. /*-{
  1629. var n = element.childNodes.length;
  1630. if (n > 0) {
  1631. return element.childNodes[n - 1].nodeValue;
  1632. }
  1633. return "";
  1634. }-*/;
  1635. private Element getLastChildElement(CustomMenuItem item) {
  1636. Element lastChildElement = item.getElement().getFirstChildElement();
  1637. while (lastChildElement.getNextSiblingElement() != null) {
  1638. lastChildElement = lastChildElement.getNextSiblingElement();
  1639. }
  1640. return lastChildElement;
  1641. }
  1642. @Override
  1643. public String getSubPartName(
  1644. com.google.gwt.user.client.Element subElement) {
  1645. if (!getElement().isOrHasChild(subElement)) {
  1646. return null;
  1647. }
  1648. Element menuItemRoot = subElement;
  1649. while (menuItemRoot != null && menuItemRoot.getParentElement() != null
  1650. && menuItemRoot.getParentElement() != getElement()) {
  1651. menuItemRoot = menuItemRoot.getParentElement().cast();
  1652. }
  1653. // "menuItemRoot" is now the root of the menu item
  1654. final int itemCount = getItems().size();
  1655. for (int i = 0; i < itemCount; i++) {
  1656. if (getItems().get(i).getElement() == menuItemRoot) {
  1657. String name = SUBPART_PREFIX + i;
  1658. return name;
  1659. }
  1660. }
  1661. return null;
  1662. }
  1663. /**
  1664. * Get menu item with given DOM element.
  1665. *
  1666. * @param element
  1667. * Element used in search
  1668. * @return Menu item or null if not found
  1669. * @deprecated As of 7.2, call or override
  1670. * {@link #getMenuItemWithElement(Element)} instead
  1671. */
  1672. @Deprecated
  1673. public CustomMenuItem getMenuItemWithElement(
  1674. com.google.gwt.user.client.Element element) {
  1675. for (int i = 0; i < items.size(); i++) {
  1676. CustomMenuItem item = items.get(i);
  1677. if (DOM.isOrHasChild(item.getElement(), element)) {
  1678. return item;
  1679. }
  1680. if (item.getSubMenu() != null) {
  1681. item = item.getSubMenu().getMenuItemWithElement(element);
  1682. if (item != null) {
  1683. return item;
  1684. }
  1685. }
  1686. }
  1687. return null;
  1688. }
  1689. /**
  1690. * Get menu item with given DOM element.
  1691. *
  1692. * @param element
  1693. * Element used in search
  1694. * @return Menu item or null if not found
  1695. *
  1696. * @since 7.2
  1697. */
  1698. public CustomMenuItem getMenuItemWithElement(Element element) {
  1699. return getMenuItemWithElement(DOM.asOld(element));
  1700. }
  1701. @Override
  1702. public void onMouseOver(MouseOverEvent event) {
  1703. LazyCloser.cancelClosing();
  1704. }
  1705. @Override
  1706. public void onMouseOut(MouseOutEvent event) {
  1707. LazyCloser.schedule();
  1708. }
  1709. protected VMenuBar getRoot() {
  1710. VMenuBar root = this;
  1711. while (root.getParentMenu() != null) {
  1712. root = root.getParentMenu();
  1713. }
  1714. return root;
  1715. }
  1716. @Override
  1717. public HandlerRegistration addTrigger(Command command,
  1718. String partInformation) {
  1719. if (partInformation == null || partInformation.isEmpty()) {
  1720. throw new IllegalArgumentException(
  1721. "The 'partInformation' parameter must contain the menu item id");
  1722. }
  1723. getTriggers().computeIfAbsent(partInformation, s -> new ArrayList<>())
  1724. .add(command);
  1725. return () -> {
  1726. List<Command> commands = getTriggers().get(partInformation);
  1727. if (commands != null) {
  1728. commands.remove(command);
  1729. }
  1730. };
  1731. }
  1732. private Map<String, List<Command>> getTriggers() {
  1733. return getRoot().triggers;
  1734. }
  1735. }