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.

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