選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

VMenuBar.java 64KB

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