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.

Navigator.java 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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.navigator;
  17. import java.io.Serializable;
  18. import java.net.URI;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.Iterator;
  23. import java.util.LinkedList;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Objects;
  27. import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
  28. import com.vaadin.server.Page;
  29. import com.vaadin.server.Page.PopStateEvent;
  30. import com.vaadin.shared.Registration;
  31. import com.vaadin.shared.util.SharedUtil;
  32. import com.vaadin.ui.Component;
  33. import com.vaadin.ui.ComponentContainer;
  34. import com.vaadin.ui.CssLayout;
  35. import com.vaadin.ui.SingleComponentContainer;
  36. import com.vaadin.ui.UI;
  37. import com.vaadin.util.ReflectTools;
  38. /**
  39. * A navigator utility that allows switching of views in a part of an
  40. * application.
  41. * <p>
  42. * The view switching can be based e.g. on URI fragments containing the view
  43. * name and parameters to the view. There are two types of parameters for views:
  44. * an optional parameter string that is included in the fragment (may be
  45. * bookmarkable).
  46. * <p>
  47. * Views can be explicitly registered or dynamically generated and listening to
  48. * view changes is possible.
  49. * <p>
  50. * Note that {@link Navigator} is not a component itself but uses a
  51. * {@link ViewDisplay} to update contents based on the state.
  52. *
  53. * @author Vaadin Ltd
  54. * @since 7.0
  55. */
  56. public class Navigator implements Serializable {
  57. // TODO investigate relationship with TouchKit navigation support
  58. private static final String DEFAULT_VIEW_SEPARATOR = "/";
  59. private static final String DEFAULT_STATE_PARAMETER_SEPARATOR = "&";
  60. private static final String DEFAULT_STATE_PARAMETER_KEY_VALUE_SEPARATOR = "=";
  61. /**
  62. * Empty view component.
  63. */
  64. public static class EmptyView extends CssLayout implements View {
  65. /**
  66. * Create minimally sized empty view.
  67. */
  68. public EmptyView() {
  69. setWidth("0px");
  70. setHeight("0px");
  71. }
  72. @Override
  73. public void enter(ViewChangeEvent event) {
  74. // nothing to do
  75. }
  76. }
  77. /**
  78. * A {@link NavigationStateManager} using path info, HTML5 push state and
  79. * {@link PopStateEvent}s to track views and enable listening to view
  80. * changes. This manager can be enabled with UI annotation
  81. * {@link PushStateNavigation}.
  82. * <p>
  83. * The part of path after UI's "root path" (UI's path without view
  84. * identifier) is used as {@link View}s identifier. The rest of the path
  85. * after the view name can be used by the developer for extra parameters for
  86. * the View.
  87. * <p>
  88. * This class is mostly for internal use by Navigator, and is only public
  89. * and static to enable testing.
  90. *
  91. * @since 8.2
  92. */
  93. public static class PushStateManager implements NavigationStateManager {
  94. private Registration popStateListenerRegistration;
  95. private UI ui;
  96. /**
  97. * Creates a new PushStateManager.
  98. *
  99. * @param ui
  100. * the UI where the Navigator is attached to
  101. */
  102. public PushStateManager(UI ui) {
  103. this.ui = ui;
  104. }
  105. @Override
  106. public void setNavigator(Navigator navigator) {
  107. if (popStateListenerRegistration != null) {
  108. popStateListenerRegistration.remove();
  109. popStateListenerRegistration = null;
  110. }
  111. if (navigator != null) {
  112. popStateListenerRegistration = ui.getPage().addPopStateListener(
  113. event -> navigator.navigateTo(getState()));
  114. }
  115. }
  116. @Override
  117. public String getState() {
  118. // Get the current URL
  119. URI location = ui.getPage().getLocation();
  120. String path = location.getPath();
  121. if (ui.getUiPathInfo() != null
  122. && path.contains(ui.getUiPathInfo())) {
  123. // Split the path from after the UI PathInfo
  124. path = path.substring(path.indexOf(ui.getUiPathInfo())
  125. + ui.getUiPathInfo().length());
  126. } else if (path.startsWith(ui.getUiRootPath())) {
  127. // Use the whole path after UI RootPath
  128. String uiRootPath = ui.getUiRootPath();
  129. path = path.substring(uiRootPath.length());
  130. } else {
  131. throw new IllegalStateException(getClass().getSimpleName()
  132. + " is unable to determine the view path from the URL.");
  133. }
  134. if (path.startsWith("/")) {
  135. // Strip leading '/'
  136. path = path.substring(1);
  137. }
  138. return path;
  139. }
  140. @Override
  141. public void setState(String state) {
  142. StringBuilder sb = new StringBuilder(ui.getUiRootPath());
  143. if (!ui.getUiRootPath().endsWith("/")) {
  144. // make sure there is a '/' between the root path and the
  145. // navigation state.
  146. sb.append('/');
  147. }
  148. sb.append(state);
  149. URI location = ui.getPage().getLocation();
  150. if (location != null) {
  151. ui.getPage().pushState(location.resolve(sb.toString()));
  152. } else {
  153. throw new IllegalStateException(
  154. "The Page of the UI does not have a location.");
  155. }
  156. }
  157. }
  158. /**
  159. * A {@link NavigationStateManager} using hashbang fragments in the Page
  160. * location URI to track views and enable listening to view changes.
  161. * <p>
  162. * A hashbang URI is one where the optional fragment or "hash" part - the
  163. * part following a # sign - is used to encode navigation state in a web
  164. * application. The advantage of this is that the fragment can be
  165. * dynamically manipulated by javascript without causing page reloads.
  166. * <p>
  167. * This class is mostly for internal use by Navigator, and is only public
  168. * and static to enable testing.
  169. * <p>
  170. * <strong>Note:</strong> Since 8.2 you can use {@link PushStateManager},
  171. * which is based on HTML5 History API. To use it, add
  172. * {@link PushStateNavigation} annotation to the UI.
  173. */
  174. public static class UriFragmentManager implements NavigationStateManager {
  175. private final Page page;
  176. private Navigator navigator;
  177. private Registration uriFragmentRegistration;
  178. /**
  179. * Creates a new URIFragmentManager and attach it to listen to URI
  180. * fragment changes of a {@link Page}.
  181. *
  182. * @param page
  183. * page whose URI fragment to get and modify
  184. */
  185. public UriFragmentManager(Page page) {
  186. this.page = page;
  187. }
  188. @Override
  189. public void setNavigator(Navigator navigator) {
  190. if (this.navigator == null && navigator != null) {
  191. uriFragmentRegistration = page.addUriFragmentChangedListener(
  192. event -> navigator.navigateTo(getState()));
  193. } else if (this.navigator != null && navigator == null) {
  194. uriFragmentRegistration.remove();
  195. }
  196. this.navigator = navigator;
  197. }
  198. @Override
  199. public String getState() {
  200. String fragment = getFragment();
  201. if (fragment == null || !fragment.startsWith("!")) {
  202. return "";
  203. } else {
  204. return fragment.substring(1);
  205. }
  206. }
  207. @Override
  208. public void setState(String state) {
  209. setFragment("!" + state);
  210. }
  211. /**
  212. * Returns the current URI fragment tracked by this UriFragentManager.
  213. *
  214. * @return The URI fragment.
  215. */
  216. protected String getFragment() {
  217. return page.getUriFragment();
  218. }
  219. /**
  220. * Sets the URI fragment to the given string.
  221. *
  222. * @param fragment
  223. * The new URI fragment.
  224. */
  225. protected void setFragment(String fragment) {
  226. page.setUriFragment(fragment, false);
  227. }
  228. }
  229. /**
  230. * A ViewDisplay that replaces the contents of a {@link ComponentContainer}
  231. * with the active {@link View}.
  232. * <p>
  233. * All components of the container are removed before adding the new view to
  234. * it.
  235. * <p>
  236. * This display only supports views that are {@link Component}s themselves.
  237. * Attempting to display a view that is not a component causes an exception
  238. * to be thrown.
  239. */
  240. public static class ComponentContainerViewDisplay implements ViewDisplay {
  241. private final ComponentContainer container;
  242. /**
  243. * Create new {@link ViewDisplay} that updates a
  244. * {@link ComponentContainer} to show the view.
  245. */
  246. public ComponentContainerViewDisplay(ComponentContainer container) {
  247. this.container = container;
  248. }
  249. @Override
  250. public void showView(View view) {
  251. container.removeAllComponents();
  252. container.addComponent(view.getViewComponent());
  253. }
  254. }
  255. /**
  256. * A ViewDisplay that replaces the contents of a
  257. * {@link SingleComponentContainer} with the active {@link View}.
  258. * <p>
  259. * This display only supports views that are {@link Component}s themselves.
  260. * Attempting to display a view that is not a component causes an exception
  261. * to be thrown.
  262. */
  263. public static class SingleComponentContainerViewDisplay
  264. implements ViewDisplay {
  265. private final SingleComponentContainer container;
  266. /**
  267. * Create new {@link ViewDisplay} that updates a
  268. * {@link SingleComponentContainer} to show the view.
  269. */
  270. public SingleComponentContainerViewDisplay(
  271. SingleComponentContainer container) {
  272. this.container = container;
  273. }
  274. @Override
  275. public void showView(View view) {
  276. container.setContent(view.getViewComponent());
  277. }
  278. }
  279. /**
  280. * A ViewProvider which supports mapping a single view name to a single
  281. * pre-initialized view instance.
  282. *
  283. * For most cases, ClassBasedViewProvider should be used instead of this.
  284. */
  285. public static class StaticViewProvider implements ViewProvider {
  286. private final String viewName;
  287. private final View view;
  288. /**
  289. * Creates a new view provider which returns a pre-created view
  290. * instance.
  291. *
  292. * @param viewName
  293. * name of the view (not null)
  294. * @param view
  295. * view instance to return (not null), reused on every
  296. * request
  297. */
  298. public StaticViewProvider(String viewName, View view) {
  299. this.viewName = viewName;
  300. this.view = view;
  301. }
  302. @Override
  303. public String getViewName(String navigationState) {
  304. if (null == navigationState) {
  305. return null;
  306. }
  307. if (navigationState.equals(viewName)
  308. || navigationState.startsWith(viewName + "/")) {
  309. return viewName;
  310. }
  311. return null;
  312. }
  313. @Override
  314. public View getView(String viewName) {
  315. if (this.viewName.equals(viewName)) {
  316. return view;
  317. }
  318. return null;
  319. }
  320. /**
  321. * Get the view name for this provider.
  322. *
  323. * @return view name for this provider
  324. */
  325. public String getViewName() {
  326. return viewName;
  327. }
  328. }
  329. /**
  330. * A ViewProvider which maps a single view name to a class to instantiate
  331. * for the view.
  332. * <p>
  333. * Note that the view class must be accessible by the class loader used by
  334. * the provider. This may require its visibility to be public.
  335. * <p>
  336. * This class is primarily for internal use by {@link Navigator}.
  337. */
  338. public static class ClassBasedViewProvider implements ViewProvider {
  339. private final String viewName;
  340. private final Class<? extends View> viewClass;
  341. /**
  342. * Create a new view provider which creates new view instances based on
  343. * a view class.
  344. *
  345. * @param viewName
  346. * name of the views to create (not null)
  347. * @param viewClass
  348. * class to instantiate when a view is requested (not null)
  349. */
  350. public ClassBasedViewProvider(String viewName,
  351. Class<? extends View> viewClass) {
  352. if (null == viewName || null == viewClass) {
  353. throw new IllegalArgumentException(
  354. "View name and class should not be null");
  355. }
  356. this.viewName = viewName;
  357. this.viewClass = viewClass;
  358. }
  359. @Override
  360. public String getViewName(String navigationState) {
  361. if (null == navigationState) {
  362. return null;
  363. }
  364. if (navigationState.equals(viewName)
  365. || navigationState.startsWith(viewName + "/")) {
  366. return viewName;
  367. }
  368. return null;
  369. }
  370. @Override
  371. public View getView(String viewName) {
  372. if (this.viewName.equals(viewName)) {
  373. return ReflectTools.createInstance(viewClass);
  374. }
  375. return null;
  376. }
  377. /**
  378. * Get the view name for this provider.
  379. *
  380. * @return view name for this provider
  381. */
  382. public String getViewName() {
  383. return viewName;
  384. }
  385. /**
  386. * Get the view class for this provider.
  387. *
  388. * @return {@link View} class
  389. */
  390. public Class<? extends View> getViewClass() {
  391. return viewClass;
  392. }
  393. }
  394. /**
  395. * The {@link UI} bound with the Navigator.
  396. */
  397. protected UI ui;
  398. /**
  399. * The {@link NavigationStateManager} that is used to get, listen to and
  400. * manipulate the navigation state used by the Navigator.
  401. */
  402. protected NavigationStateManager stateManager;
  403. /**
  404. * The {@link ViewDisplay} used by the Navigator.
  405. */
  406. protected ViewDisplay display;
  407. private View currentView = null;
  408. private List<ViewChangeListener> listeners = new LinkedList<>();
  409. private List<ViewProvider> providers = new LinkedList<>();
  410. private String currentNavigationState = null;
  411. private ViewProvider errorProvider;
  412. /**
  413. * Creates a navigator that is tracking the active view using URI fragments
  414. * of the {@link Page} containing the given UI and replacing the contents of
  415. * a {@link ComponentContainer} with the active view.
  416. * <p>
  417. * All components of the container are removed each time before adding the
  418. * active {@link View}. Views must implement {@link Component} when using
  419. * this constructor.
  420. * <p>
  421. * Navigation is automatically initiated after {@code UI.init()} if a
  422. * navigator was created. If at a later point changes are made to the
  423. * navigator, {@code navigator.navigateTo(navigator.getState())} may need to
  424. * be explicitly called to ensure the current view matches the navigation
  425. * state.
  426. *
  427. * @param ui
  428. * The UI to which this Navigator is attached.
  429. * @param container
  430. * The ComponentContainer whose contents should be replaced with
  431. * the active view on view change
  432. */
  433. public Navigator(UI ui, ComponentContainer container) {
  434. this(ui, new ComponentContainerViewDisplay(container));
  435. }
  436. /**
  437. * Creates a navigator that is tracking the active view using URI fragments
  438. * of the {@link Page} containing the given UI and replacing the contents of
  439. * a {@link SingleComponentContainer} with the active view.
  440. * <p>
  441. * Views must implement {@link Component} when using this constructor.
  442. * <p>
  443. * Navigation is automatically initiated after {@code UI.init()} if a
  444. * navigator was created. If at a later point changes are made to the
  445. * navigator, {@code navigator.navigateTo(navigator.getState())} may need to
  446. * be explicitly called to ensure the current view matches the navigation
  447. * state.
  448. *
  449. * @param ui
  450. * The UI to which this Navigator is attached.
  451. * @param container
  452. * The SingleComponentContainer whose contents should be replaced
  453. * with the active view on view change
  454. */
  455. public Navigator(UI ui, SingleComponentContainer container) {
  456. this(ui, new SingleComponentContainerViewDisplay(container));
  457. }
  458. /**
  459. * Creates a navigator that is tracking the active view using URI fragments
  460. * of the {@link Page} containing the given UI.
  461. * <p>
  462. * Navigation is automatically initiated after {@code UI.init()} if a
  463. * navigator was created. If at a later point changes are made to the
  464. * navigator, {@code navigator.navigateTo(navigator.getState())} may need to
  465. * be explicitly called to ensure the current view matches the navigation
  466. * state.
  467. *
  468. * @param ui
  469. * The UI to which this Navigator is attached.
  470. * @param display
  471. * The ViewDisplay used to display the views.
  472. */
  473. public Navigator(UI ui, ViewDisplay display) {
  474. this(ui, null, display);
  475. }
  476. /**
  477. * Creates a navigator.
  478. * <p>
  479. * When a custom navigation state manager is not needed, use one of the
  480. * other constructors which use a URI fragment based state manager.
  481. * <p>
  482. * Navigation is automatically initiated after {@code UI.init()} if a
  483. * navigator was created. If at a later point changes are made to the
  484. * navigator, {@code navigator.navigateTo(navigator.getState())} may need to
  485. * be explicitly called to ensure the current view matches the navigation
  486. * state.
  487. *
  488. * @param ui
  489. * The UI to which this Navigator is attached.
  490. * @param stateManager
  491. * The NavigationStateManager keeping track of the active view
  492. * and enabling bookmarking and direct navigation or null to use
  493. * the default implementation
  494. * @param display
  495. * The ViewDisplay used to display the views handled by this
  496. * navigator
  497. */
  498. public Navigator(UI ui, NavigationStateManager stateManager,
  499. ViewDisplay display) {
  500. init(ui, stateManager, display);
  501. }
  502. /**
  503. * Creates a navigator. This method is for use by dependency injection
  504. * frameworks etc. and must be followed by a call to
  505. * {@link #init(UI, NavigationStateManager, ViewDisplay)} before use.
  506. *
  507. * @since 7.6
  508. */
  509. protected Navigator() {
  510. }
  511. /**
  512. * Initializes a navigator created with the no arguments constructor.
  513. * <p>
  514. * When a custom navigation state manager is not needed, use null to create
  515. * a default one based on URI fragments.
  516. * <p>
  517. * Navigation is automatically initiated after {@code UI.init()} if a
  518. * navigator was created. If at a later point changes are made to the
  519. * navigator, {@code navigator.navigateTo(navigator.getState())} may need to
  520. * be explicitly called to ensure the current view matches the navigation
  521. * state.
  522. *
  523. * @since 7.6
  524. * @param ui
  525. * The UI to which this Navigator is attached.
  526. * @param stateManager
  527. * The NavigationStateManager keeping track of the active view
  528. * and enabling bookmarking and direct navigation or null for
  529. * default
  530. * @param display
  531. * The ViewDisplay used to display the views handled by this
  532. * navigator
  533. */
  534. protected void init(UI ui, NavigationStateManager stateManager,
  535. ViewDisplay display) {
  536. this.ui = ui;
  537. this.ui.setNavigator(this);
  538. if (stateManager == null) {
  539. stateManager = createNavigationStateManager(ui);
  540. }
  541. if (stateManager != null && this.stateManager != null
  542. && stateManager != this.stateManager) {
  543. this.stateManager.setNavigator(null);
  544. }
  545. this.stateManager = stateManager;
  546. this.stateManager.setNavigator(this);
  547. this.display = display;
  548. }
  549. /**
  550. * Creates a navigation state manager for given UI. This method should take
  551. * into account any navigation related annotations.
  552. *
  553. * @param ui
  554. * the ui
  555. * @return the navigation state manager
  556. *
  557. * @since 8.2
  558. */
  559. protected NavigationStateManager createNavigationStateManager(UI ui) {
  560. if (ui.getClass().getAnnotation(PushStateNavigation.class) != null) {
  561. return new PushStateManager(ui);
  562. }
  563. // Fall back to old default
  564. return new UriFragmentManager(ui.getPage());
  565. }
  566. /**
  567. * Navigates to a view and initialize the view with given parameters.
  568. * <p>
  569. * The view string consists of a view name optionally followed by a slash
  570. * and a parameters part that is passed as-is to the view. ViewProviders are
  571. * used to find and create the correct type of view.
  572. * <p>
  573. * If multiple providers return a matching view, the view with the longest
  574. * name is selected. This way, e.g. hierarchies of subviews can be
  575. * registered like "admin/", "admin/users", "admin/settings" and the longest
  576. * match is used.
  577. * <p>
  578. * If the view being deactivated indicates it wants a confirmation for the
  579. * navigation operation, the user is asked for the confirmation.
  580. * <p>
  581. * Registered {@link ViewChangeListener}s are called upon successful view
  582. * change.
  583. *
  584. * @param navigationState
  585. * view name and parameters
  586. *
  587. * @throws IllegalArgumentException
  588. * if <code>navigationState</code> does not map to a known view
  589. * and no error view is registered
  590. */
  591. public void navigateTo(String navigationState) {
  592. ViewProvider longestViewNameProvider = getViewProvider(navigationState);
  593. String longestViewName = longestViewNameProvider == null ? null
  594. : longestViewNameProvider.getViewName(navigationState);
  595. View viewWithLongestName = null;
  596. if (longestViewName != null) {
  597. viewWithLongestName = longestViewNameProvider
  598. .getView(longestViewName);
  599. }
  600. if (viewWithLongestName == null && errorProvider != null) {
  601. longestViewName = errorProvider.getViewName(navigationState);
  602. viewWithLongestName = errorProvider.getView(longestViewName);
  603. }
  604. if (viewWithLongestName == null) {
  605. throw new IllegalArgumentException(
  606. "Trying to navigate to an unknown state '" + navigationState
  607. + "' and an error view provider not present");
  608. }
  609. String parameters = "";
  610. if (navigationState.length() > longestViewName.length() + 1) {
  611. parameters = navigationState
  612. .substring(longestViewName.length() + 1);
  613. } else if (navigationState.endsWith("/")) {
  614. navigationState = navigationState.substring(0,
  615. navigationState.length() - 1);
  616. }
  617. if (getCurrentView() == null
  618. || !SharedUtil.equals(getCurrentView(), viewWithLongestName)
  619. || !SharedUtil.equals(currentNavigationState,
  620. navigationState)) {
  621. navigateTo(viewWithLongestName, longestViewName, parameters);
  622. } else {
  623. updateNavigationState(new ViewChangeEvent(this, getCurrentView(),
  624. viewWithLongestName, longestViewName, parameters));
  625. }
  626. }
  627. /**
  628. * Internal method activating a view, setting its parameters and calling
  629. * listeners.
  630. * <p>
  631. * This method also verifies that the user is allowed to perform the
  632. * navigation operation.
  633. *
  634. * @param view
  635. * view to activate
  636. * @param viewName
  637. * (optional) name of the view or null not to change the
  638. * navigation state
  639. * @param parameters
  640. * parameters passed in the navigation state to the view
  641. */
  642. protected void navigateTo(View view, String viewName, String parameters) {
  643. runAfterLeaveConfirmation(
  644. () -> performNavigateTo(view, viewName, parameters));
  645. }
  646. /**
  647. * Triggers {@link View#beforeLeave(ViewBeforeLeaveEvent)} for the current
  648. * view with the given action.
  649. * <p>
  650. * This method is typically called by
  651. * {@link #navigateTo(View, String, String)} but can be called from
  652. * application code when you want to e.g. show a confirmation dialog before
  653. * perfoming an action which is not a navigation but which would cause the
  654. * view to be hidden, e.g. logging out.
  655. * <p>
  656. * Note that this method will not trigger any {@link ViewChangeListener}s as
  657. * it does not navigate to a new view. Use {@link #navigateTo(String)} to
  658. * change views and trigger all listeners.
  659. *
  660. * @param action
  661. * the action to execute when the view confirms it is ok to leave
  662. * @since 8.1
  663. */
  664. public void runAfterLeaveConfirmation(ViewLeaveAction action) {
  665. View currentView = getCurrentView();
  666. if (currentView == null) {
  667. action.run();
  668. } else {
  669. ViewBeforeLeaveEvent beforeLeaveEvent = new ViewBeforeLeaveEvent(
  670. this, action);
  671. currentView.beforeLeave(beforeLeaveEvent);
  672. if (!beforeLeaveEvent.isNavigateRun()) {
  673. // The event handler prevented navigation
  674. // Revert URL to previous state in case the navigation was
  675. // caused by the back-button
  676. revertNavigation();
  677. }
  678. }
  679. }
  680. /**
  681. * Internal method for activating a view, setting its parameters and calling
  682. * listeners.
  683. * <p>
  684. * Invoked after the current view has confirmed that leaving is ok.
  685. * <p>
  686. * This method also verifies that the user is allowed to perform the
  687. * navigation operation.
  688. *
  689. * @param view
  690. * view to activate
  691. * @param viewName
  692. * (optional) name of the view or null not to change the
  693. * navigation state
  694. * @param parameters
  695. * parameters passed in the navigation state to the view
  696. * @since 8.1
  697. */
  698. protected void performNavigateTo(View view, String viewName,
  699. String parameters) {
  700. ViewChangeEvent event = new ViewChangeEvent(this, currentView, view,
  701. viewName, parameters);
  702. boolean navigationAllowed = beforeViewChange(event);
  703. if (!navigationAllowed) {
  704. // #10901. Revert URL to previous state if back-button navigation
  705. // was canceled
  706. revertNavigation();
  707. return;
  708. }
  709. updateNavigationState(event);
  710. if (getDisplay() != null) {
  711. getDisplay().showView(view);
  712. }
  713. switchView(event);
  714. view.enter(event);
  715. fireAfterViewChange(event);
  716. }
  717. /**
  718. * Check whether view change is allowed by view change listeners (
  719. * {@link ViewChangeListener#beforeViewChange(ViewChangeEvent)}).
  720. *
  721. * This method can be overridden to extend the behavior, and should not be
  722. * called directly except by {@link #navigateTo(View, String, String)}.
  723. *
  724. * @since 7.6
  725. * @param event
  726. * the event to fire as the before view change event
  727. * @return true if view change is allowed
  728. */
  729. protected boolean beforeViewChange(ViewChangeEvent event) {
  730. return fireBeforeViewChange(event);
  731. }
  732. /**
  733. * Revert the changes to the navigation state. When navigation fails, this
  734. * method can be called by {@link #navigateTo(View, String, String)} to
  735. * revert the URL fragment to point to the previous view to which navigation
  736. * succeeded.
  737. *
  738. * This method should only be called by
  739. * {@link #navigateTo(View, String, String)}. Normally it should not be
  740. * overridden, but can be by frameworks that need to hook into view change
  741. * cancellations of this type.
  742. *
  743. * @since 7.6
  744. */
  745. protected void revertNavigation() {
  746. if (currentNavigationState != null) {
  747. getStateManager().setState(currentNavigationState);
  748. }
  749. }
  750. /**
  751. * Update the internal state of the navigator (parameters, previous
  752. * successful URL fragment navigated to) when navigation succeeds.
  753. *
  754. * Normally this method should not be overridden nor called directly from
  755. * application code, but it can be called by a custom implementation of
  756. * {@link #navigateTo(View, String, String)}.
  757. *
  758. * @since 7.6
  759. * @param event
  760. * a view change event with details of the change
  761. */
  762. protected void updateNavigationState(ViewChangeEvent event) {
  763. String viewName = event.getViewName();
  764. String parameters = event.getParameters();
  765. if (null != viewName && getStateManager() != null) {
  766. String navigationState = viewName;
  767. if (!parameters.isEmpty()) {
  768. navigationState += "/" + parameters;
  769. }
  770. if (!navigationState.equals(getStateManager().getState())) {
  771. getStateManager().setState(navigationState);
  772. }
  773. currentNavigationState = navigationState;
  774. }
  775. }
  776. /**
  777. * Update the internal state of the navigator to reflect the actual
  778. * switching of views.
  779. *
  780. * This method should only be called by
  781. * {@link #navigateTo(View, String, String)} between showing the view and
  782. * calling {@link View#enter(ViewChangeEvent)}. If this method is
  783. * overridden, the overriding version must call the super method.
  784. *
  785. * @since 7.6
  786. * @param event
  787. * a view change event with details of the change
  788. */
  789. protected void switchView(ViewChangeEvent event) {
  790. currentView = event.getNewView();
  791. }
  792. /**
  793. * Fires an event before an imminent view change.
  794. * <p>
  795. * Listeners are called in registration order. If any listener returns
  796. * <code>false</code>, the rest of the listeners are not called and the view
  797. * change is blocked.
  798. * <p>
  799. * The view change listeners may also e.g. open a warning or question dialog
  800. * and save the parameters to re-initiate the navigation operation upon user
  801. * action.
  802. *
  803. * @param event
  804. * view change event (not null, view change not yet performed)
  805. * @return true if the view change should be allowed, false to silently
  806. * block the navigation operation
  807. */
  808. protected boolean fireBeforeViewChange(ViewChangeEvent event) {
  809. // a copy of the listener list is needed to avoid
  810. // ConcurrentModificationException as a listener can add/remove
  811. // listeners
  812. for (ViewChangeListener l : new ArrayList<>(listeners)) {
  813. if (!l.beforeViewChange(event)) {
  814. return false;
  815. }
  816. }
  817. return true;
  818. }
  819. /**
  820. * Returns the {@link NavigationStateManager} that is used to get, listen to
  821. * and manipulate the navigation state used by this Navigator.
  822. *
  823. * @return NavigationStateManager in use
  824. */
  825. protected NavigationStateManager getStateManager() {
  826. return stateManager;
  827. }
  828. /**
  829. * Returns the current navigation state reported by this Navigator's
  830. * {@link NavigationStateManager}.
  831. *
  832. * @return The navigation state.
  833. */
  834. public String getState() {
  835. return getStateManager().getState();
  836. }
  837. /**
  838. * Returns the current navigation state reported by this Navigator's
  839. * {@link NavigationStateManager} as Map<String, String> where each key
  840. * represents a parameter in the state.
  841. *
  842. * Uses {@literal &} as parameter separator. If the state contains
  843. * {@literal #!view/foo&bar=baz} then this method will return a map
  844. * containing {@literal foo => ""} and {@literal bar => baz}.
  845. *
  846. * @return The parameters from the navigation state as a map
  847. * @see #getStateParameterMap(String)
  848. * @since 8.1
  849. */
  850. public Map<String, String> getStateParameterMap() {
  851. return getStateParameterMap(DEFAULT_STATE_PARAMETER_SEPARATOR);
  852. }
  853. /**
  854. * Returns the current navigation state reported by this Navigator's
  855. * {@link NavigationStateManager} as Map<String, String> where each key
  856. * represents a parameter in the state. The state parameter separator
  857. * character needs to be specified with the separator.
  858. *
  859. * @param separator
  860. * the string (typically one character) used to separate values
  861. * from each other
  862. * @return The parameters from the navigation state as a map
  863. * @see #getStateParameterMap()
  864. * @since 8.1
  865. */
  866. public Map<String, String> getStateParameterMap(String separator) {
  867. return parseStateParameterMap(Objects.requireNonNull(separator));
  868. }
  869. /**
  870. * Parses the state parameter to a map using the given separator string.
  871. *
  872. * @param separator
  873. * the string (typically one character) used to separate values
  874. * from each other
  875. * @return The navigation state as Map<String, String>.
  876. * @since 8.1
  877. */
  878. protected Map<String, String> parseStateParameterMap(String separator) {
  879. if (getState() == null || getState().isEmpty()) {
  880. return Collections.emptyMap();
  881. }
  882. String state = getState();
  883. int viewSeparatorLocation = state.indexOf(DEFAULT_VIEW_SEPARATOR);
  884. String parameterString;
  885. if (viewSeparatorLocation == -1) {
  886. parameterString = "";
  887. } else {
  888. parameterString = state.substring(viewSeparatorLocation + 1,
  889. state.length());
  890. }
  891. return parseParameterStringToMap(parameterString, separator);
  892. }
  893. /**
  894. * Parses the given parameter string to a map using the given separator
  895. * string.
  896. *
  897. * @param parameterString
  898. * the parameter string to parse
  899. * @param separator
  900. * the string (typically one character) used to separate values
  901. * from each other
  902. * @return The navigation state as Map<String, String>.
  903. * @since 8.1
  904. */
  905. protected Map<String, String> parseParameterStringToMap(
  906. String parameterString, String separator) {
  907. if (parameterString.isEmpty()) {
  908. return Collections.emptyMap();
  909. }
  910. Map<String, String> parameterMap = new HashMap<>();
  911. String[] parameters = parameterString.split(separator);
  912. for (String parameter : parameters) {
  913. String[] keyAndValue = parameter
  914. .split(DEFAULT_STATE_PARAMETER_KEY_VALUE_SEPARATOR);
  915. parameterMap.put(keyAndValue[0],
  916. keyAndValue.length > 1 ? keyAndValue[1] : "");
  917. }
  918. return parameterMap;
  919. }
  920. /**
  921. * Return the {@link ViewDisplay} used by the navigator.
  922. *
  923. * @return the ViewDisplay used for displaying views
  924. */
  925. public ViewDisplay getDisplay() {
  926. return display;
  927. }
  928. public UI getUI() {
  929. return ui;
  930. }
  931. /**
  932. * Return the currently active view.
  933. *
  934. * @since 7.6
  935. * @return current view
  936. */
  937. public View getCurrentView() {
  938. return currentView;
  939. }
  940. /**
  941. * Fires an event after the current view has changed.
  942. * <p>
  943. * Listeners are called in registration order.
  944. *
  945. * @param event
  946. * view change event (not null)
  947. */
  948. protected void fireAfterViewChange(ViewChangeEvent event) {
  949. // a copy of the listener list is needed to avoid
  950. // ConcurrentModificationException as a listener can add/remove
  951. // listeners
  952. for (ViewChangeListener l : new ArrayList<>(listeners)) {
  953. l.afterViewChange(event);
  954. }
  955. }
  956. /**
  957. * Registers a static, pre-initialized view instance for a view name.
  958. * <p>
  959. * Registering another view with a name that is already registered
  960. * overwrites the old registration of the same type.
  961. * <p>
  962. * Note that a view should not be shared between UIs (for instance, it
  963. * should not be a static field in a UI subclass).
  964. *
  965. * @param viewName
  966. * String that identifies a view (not null nor empty string)
  967. * @param view
  968. * {@link View} instance (not null)
  969. */
  970. public void addView(String viewName, View view) {
  971. // Check parameters
  972. if (viewName == null || view == null) {
  973. throw new IllegalArgumentException(
  974. "view and viewName must be non-null");
  975. }
  976. removeView(viewName);
  977. addProvider(new StaticViewProvider(viewName, view));
  978. }
  979. /**
  980. * Registers a view class for a view name.
  981. * <p>
  982. * Registering another view with a name that is already registered
  983. * overwrites the old registration of the same type.
  984. * <p>
  985. * A new view instance is created every time a view is requested.
  986. *
  987. * @param viewName
  988. * String that identifies a view (not null nor empty string)
  989. * @param viewClass
  990. * {@link View} class to instantiate when a view is requested
  991. * (not null)
  992. */
  993. public void addView(String viewName, Class<? extends View> viewClass) {
  994. // Check parameters
  995. if (viewName == null || viewClass == null) {
  996. throw new IllegalArgumentException(
  997. "view and viewClass must be non-null");
  998. }
  999. removeView(viewName);
  1000. addProvider(new ClassBasedViewProvider(viewName, viewClass));
  1001. }
  1002. /**
  1003. * Removes a view from navigator.
  1004. * <p>
  1005. * This method only applies to views registered using
  1006. * {@link #addView(String, View)} or {@link #addView(String, Class)}.
  1007. *
  1008. * @param viewName
  1009. * name of the view to remove
  1010. */
  1011. public void removeView(String viewName) {
  1012. Iterator<ViewProvider> it = providers.iterator();
  1013. while (it.hasNext()) {
  1014. ViewProvider provider = it.next();
  1015. if (provider instanceof StaticViewProvider) {
  1016. StaticViewProvider staticProvider = (StaticViewProvider) provider;
  1017. if (staticProvider.getViewName().equals(viewName)) {
  1018. it.remove();
  1019. }
  1020. } else if (provider instanceof ClassBasedViewProvider) {
  1021. ClassBasedViewProvider classBasedProvider = (ClassBasedViewProvider) provider;
  1022. if (classBasedProvider.getViewName().equals(viewName)) {
  1023. it.remove();
  1024. }
  1025. }
  1026. }
  1027. }
  1028. /**
  1029. * Registers a view provider (factory).
  1030. * <p>
  1031. * Providers are called in order of registration until one that can handle
  1032. * the requested view name is found.
  1033. *
  1034. * @param provider
  1035. * provider to register, not <code>null</code>
  1036. * @throws IllegalArgumentException
  1037. * if the provided view provider is <code>null</code>
  1038. */
  1039. public void addProvider(ViewProvider provider) {
  1040. if (provider == null) {
  1041. throw new IllegalArgumentException(
  1042. "Cannot add a null view provider");
  1043. }
  1044. providers.add(provider);
  1045. }
  1046. /**
  1047. * Unregister a view provider (factory).
  1048. *
  1049. * @param provider
  1050. * provider to unregister
  1051. */
  1052. public void removeProvider(ViewProvider provider) {
  1053. providers.remove(provider);
  1054. }
  1055. /**
  1056. * Registers a view class that is instantiated when no other view matches
  1057. * the navigation state. This implicitly sets an appropriate error view
  1058. * provider and overrides any previous
  1059. * {@link #setErrorProvider(ViewProvider)} call.
  1060. * <p>
  1061. * Note that an error view should not be shared between UIs (for instance,
  1062. * it should not be a static field in a UI subclass).
  1063. *
  1064. * @param viewClass
  1065. * The View class whose instance should be used as the error
  1066. * view.
  1067. */
  1068. public void setErrorView(final Class<? extends View> viewClass) {
  1069. setErrorProvider(new ViewProvider() {
  1070. @Override
  1071. public View getView(String viewName) {
  1072. return ReflectTools.createInstance(viewClass);
  1073. }
  1074. @Override
  1075. public String getViewName(String navigationState) {
  1076. return navigationState;
  1077. }
  1078. });
  1079. }
  1080. /**
  1081. * Registers a view that is displayed when no other view matches the
  1082. * navigation state. This implicitly sets an appropriate error view provider
  1083. * and overrides any previous {@link #setErrorProvider(ViewProvider)} call.
  1084. *
  1085. * @param view
  1086. * The View that should be used as the error view.
  1087. */
  1088. public void setErrorView(final View view) {
  1089. setErrorProvider(new ViewProvider() {
  1090. @Override
  1091. public View getView(String viewName) {
  1092. return view;
  1093. }
  1094. @Override
  1095. public String getViewName(String navigationState) {
  1096. return navigationState;
  1097. }
  1098. });
  1099. }
  1100. /**
  1101. * Registers a view provider that is queried for a view when no other view
  1102. * matches the navigation state. An error view provider should match any
  1103. * navigation state, but could return different views for different states.
  1104. * Its <code>getViewName(String navigationState)</code> should return
  1105. * <code>navigationState</code>.
  1106. *
  1107. * @param provider
  1108. */
  1109. public void setErrorProvider(ViewProvider provider) {
  1110. errorProvider = provider;
  1111. }
  1112. /**
  1113. * Listen to changes of the active view.
  1114. * <p>
  1115. * Registered listeners are invoked in registration order before (
  1116. * {@link ViewChangeListener#beforeViewChange(ViewChangeEvent)
  1117. * beforeViewChange()}) and after (
  1118. * {@link ViewChangeListener#afterViewChange(ViewChangeEvent)
  1119. * afterViewChange()}) a view change occurs.
  1120. *
  1121. * @param listener
  1122. * Listener to invoke during a view change.
  1123. * @since 8.0
  1124. */
  1125. public Registration addViewChangeListener(ViewChangeListener listener) {
  1126. listeners.add(listener);
  1127. return () -> listeners.remove(listener);
  1128. }
  1129. /**
  1130. * Removes a view change listener.
  1131. *
  1132. * @param listener
  1133. * Listener to remove.
  1134. * @deprecated use a {@link Registration} object returned by
  1135. * {@link #addViewChangeListener(ViewChangeListener)} to remove
  1136. * a listener
  1137. */
  1138. @Deprecated
  1139. public void removeViewChangeListener(ViewChangeListener listener) {
  1140. listeners.remove(listener);
  1141. }
  1142. /**
  1143. * Get view provider that handles the given {@code state}.
  1144. *
  1145. * @param state
  1146. * state string
  1147. * @return suitable provider
  1148. */
  1149. protected ViewProvider getViewProvider(String state) {
  1150. String longestViewName = null;
  1151. ViewProvider longestViewNameProvider = null;
  1152. for (ViewProvider provider : providers) {
  1153. String viewName = provider.getViewName(state);
  1154. if (null != viewName && (longestViewName == null
  1155. || viewName.length() > longestViewName.length())) {
  1156. longestViewName = viewName;
  1157. longestViewNameProvider = provider;
  1158. }
  1159. }
  1160. return longestViewNameProvider;
  1161. }
  1162. /**
  1163. * Creates view change event for given {@code view}, {@code viewName} and
  1164. * {@code parameters}.
  1165. *
  1166. * @since 7.6.7
  1167. */
  1168. public void destroy() {
  1169. stateManager.setNavigator(null);
  1170. ui.setNavigator(null);
  1171. }
  1172. /**
  1173. * Returns the current navigation state for which the
  1174. * {@link #getCurrentView()} has been constructed. This may differ to
  1175. * {@link #getState()} in case the URL has been changed on the browser and
  1176. * the navigator wasn't yet given an opportunity to construct new view. The
  1177. * state is in the form of
  1178. * <code>current-view-name/optional/parameters</code>
  1179. *
  1180. * @return the current navigation state, may be {@code null}.
  1181. */
  1182. public String getCurrentNavigationState() {
  1183. return currentNavigationState;
  1184. }
  1185. }