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

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