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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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. * <p>
  832. * When the navigation is triggered by the browser (for example by pressing
  833. * the back or forward button in the browser), the navigation state may
  834. * already have been updated to reflect the new address, before the
  835. * {@link #navigateTo(String)} is notified.
  836. *
  837. * @return The navigation state.
  838. */
  839. public String getState() {
  840. return getStateManager().getState();
  841. }
  842. /**
  843. * Returns the current navigation state reported by this Navigator's
  844. * {@link NavigationStateManager} as Map<String, String> where each key
  845. * represents a parameter in the state.
  846. *
  847. * Uses {@literal &} as parameter separator. If the state contains
  848. * {@literal #!view/foo&bar=baz} then this method will return a map
  849. * containing {@literal foo => ""} and {@literal bar => baz}.
  850. *
  851. * @return The parameters from the navigation state as a map
  852. * @see #getStateParameterMap(String)
  853. * @since 8.1
  854. */
  855. public Map<String, String> getStateParameterMap() {
  856. return getStateParameterMap(DEFAULT_STATE_PARAMETER_SEPARATOR);
  857. }
  858. /**
  859. * Returns the current navigation state reported by this Navigator's
  860. * {@link NavigationStateManager} as Map<String, String> where each key
  861. * represents a parameter in the state. The state parameter separator
  862. * character needs to be specified with the separator.
  863. *
  864. * @param separator
  865. * the string (typically one character) used to separate values
  866. * from each other
  867. * @return The parameters from the navigation state as a map
  868. * @see #getStateParameterMap()
  869. * @since 8.1
  870. */
  871. public Map<String, String> getStateParameterMap(String separator) {
  872. return parseStateParameterMap(Objects.requireNonNull(separator));
  873. }
  874. /**
  875. * Parses the state parameter to a map using the given separator string.
  876. *
  877. * @param separator
  878. * the string (typically one character) used to separate values
  879. * from each other
  880. * @return The navigation state as Map<String, String>.
  881. * @since 8.1
  882. */
  883. protected Map<String, String> parseStateParameterMap(String separator) {
  884. if (getState() == null || getState().isEmpty()) {
  885. return Collections.emptyMap();
  886. }
  887. String state = getState();
  888. int viewSeparatorLocation = state.indexOf(DEFAULT_VIEW_SEPARATOR);
  889. String parameterString;
  890. if (viewSeparatorLocation == -1) {
  891. parameterString = "";
  892. } else {
  893. parameterString = state.substring(viewSeparatorLocation + 1,
  894. state.length());
  895. }
  896. return parseParameterStringToMap(parameterString, separator);
  897. }
  898. /**
  899. * Parses the given parameter string to a map using the given separator
  900. * string.
  901. *
  902. * @param parameterString
  903. * the parameter string to parse
  904. * @param separator
  905. * the string (typically one character) used to separate values
  906. * from each other
  907. * @return The navigation state as Map<String, String>.
  908. * @since 8.1
  909. */
  910. protected Map<String, String> parseParameterStringToMap(
  911. String parameterString, String separator) {
  912. if (parameterString.isEmpty()) {
  913. return Collections.emptyMap();
  914. }
  915. Map<String, String> parameterMap = new HashMap<>();
  916. String[] parameters = parameterString.split(separator);
  917. for (String parameter : parameters) {
  918. String[] keyAndValue = parameter
  919. .split(DEFAULT_STATE_PARAMETER_KEY_VALUE_SEPARATOR);
  920. parameterMap.put(keyAndValue[0],
  921. keyAndValue.length > 1 ? keyAndValue[1] : "");
  922. }
  923. return parameterMap;
  924. }
  925. /**
  926. * Return the {@link ViewDisplay} used by the navigator.
  927. *
  928. * @return the ViewDisplay used for displaying views
  929. */
  930. public ViewDisplay getDisplay() {
  931. return display;
  932. }
  933. public UI getUI() {
  934. return ui;
  935. }
  936. /**
  937. * Return the currently active view.
  938. *
  939. * @since 7.6
  940. * @return current view
  941. */
  942. public View getCurrentView() {
  943. return currentView;
  944. }
  945. /**
  946. * Fires an event after the current view has changed.
  947. * <p>
  948. * Listeners are called in registration order.
  949. *
  950. * @param event
  951. * view change event (not null)
  952. */
  953. protected void fireAfterViewChange(ViewChangeEvent event) {
  954. // a copy of the listener list is needed to avoid
  955. // ConcurrentModificationException as a listener can add/remove
  956. // listeners
  957. for (ViewChangeListener l : new ArrayList<>(listeners)) {
  958. l.afterViewChange(event);
  959. }
  960. }
  961. /**
  962. * Registers a static, pre-initialized view instance for a view name.
  963. * <p>
  964. * Registering another view with a name that is already registered
  965. * overwrites the old registration of the same type.
  966. * <p>
  967. * Note that a view should not be shared between UIs (for instance, it
  968. * should not be a static field in a UI subclass).
  969. *
  970. * @param viewName
  971. * String that identifies a view (not null nor empty string)
  972. * @param view
  973. * {@link View} instance (not null)
  974. */
  975. public void addView(String viewName, View view) {
  976. // Check parameters
  977. if (viewName == null || view == null) {
  978. throw new IllegalArgumentException(
  979. "view and viewName must be non-null");
  980. }
  981. removeView(viewName);
  982. addProvider(new StaticViewProvider(viewName, view));
  983. }
  984. /**
  985. * Registers a view class for a view name.
  986. * <p>
  987. * Registering another view with a name that is already registered
  988. * overwrites the old registration of the same type.
  989. * <p>
  990. * A new view instance is created every time a view is requested.
  991. *
  992. * @param viewName
  993. * String that identifies a view (not null nor empty string)
  994. * @param viewClass
  995. * {@link View} class to instantiate when a view is requested
  996. * (not null)
  997. */
  998. public void addView(String viewName, Class<? extends View> viewClass) {
  999. // Check parameters
  1000. if (viewName == null || viewClass == null) {
  1001. throw new IllegalArgumentException(
  1002. "view and viewClass must be non-null");
  1003. }
  1004. removeView(viewName);
  1005. addProvider(new ClassBasedViewProvider(viewName, viewClass));
  1006. }
  1007. /**
  1008. * Removes a view from navigator.
  1009. * <p>
  1010. * This method only applies to views registered using
  1011. * {@link #addView(String, View)} or {@link #addView(String, Class)}.
  1012. *
  1013. * @param viewName
  1014. * name of the view to remove
  1015. */
  1016. public void removeView(String viewName) {
  1017. Iterator<ViewProvider> it = providers.iterator();
  1018. while (it.hasNext()) {
  1019. ViewProvider provider = it.next();
  1020. if (provider instanceof StaticViewProvider) {
  1021. StaticViewProvider staticProvider = (StaticViewProvider) provider;
  1022. if (staticProvider.getViewName().equals(viewName)) {
  1023. it.remove();
  1024. }
  1025. } else if (provider instanceof ClassBasedViewProvider) {
  1026. ClassBasedViewProvider classBasedProvider = (ClassBasedViewProvider) provider;
  1027. if (classBasedProvider.getViewName().equals(viewName)) {
  1028. it.remove();
  1029. }
  1030. }
  1031. }
  1032. }
  1033. /**
  1034. * Registers a view provider (factory).
  1035. * <p>
  1036. * Providers are called in order of registration until one that can handle
  1037. * the requested view name is found.
  1038. *
  1039. * @param provider
  1040. * provider to register, not <code>null</code>
  1041. * @throws IllegalArgumentException
  1042. * if the provided view provider is <code>null</code>
  1043. */
  1044. public void addProvider(ViewProvider provider) {
  1045. if (provider == null) {
  1046. throw new IllegalArgumentException(
  1047. "Cannot add a null view provider");
  1048. }
  1049. providers.add(provider);
  1050. }
  1051. /**
  1052. * Unregister a view provider (factory).
  1053. *
  1054. * @param provider
  1055. * provider to unregister
  1056. */
  1057. public void removeProvider(ViewProvider provider) {
  1058. providers.remove(provider);
  1059. }
  1060. /**
  1061. * Registers a view class that is instantiated when no other view matches
  1062. * the navigation state. This implicitly sets an appropriate error view
  1063. * provider and overrides any previous
  1064. * {@link #setErrorProvider(ViewProvider)} call.
  1065. * <p>
  1066. * Note that an error view should not be shared between UIs (for instance,
  1067. * it should not be a static field in a UI subclass).
  1068. *
  1069. * @param viewClass
  1070. * The View class whose instance should be used as the error
  1071. * view.
  1072. */
  1073. public void setErrorView(final Class<? extends View> viewClass) {
  1074. setErrorProvider(new ViewProvider() {
  1075. @Override
  1076. public View getView(String viewName) {
  1077. return ReflectTools.createInstance(viewClass);
  1078. }
  1079. @Override
  1080. public String getViewName(String navigationState) {
  1081. return navigationState;
  1082. }
  1083. });
  1084. }
  1085. /**
  1086. * Registers a view that is displayed when no other view matches the
  1087. * navigation state. This implicitly sets an appropriate error view provider
  1088. * and overrides any previous {@link #setErrorProvider(ViewProvider)} call.
  1089. *
  1090. * @param view
  1091. * The View that should be used as the error view.
  1092. */
  1093. public void setErrorView(final View view) {
  1094. setErrorProvider(new ViewProvider() {
  1095. @Override
  1096. public View getView(String viewName) {
  1097. return view;
  1098. }
  1099. @Override
  1100. public String getViewName(String navigationState) {
  1101. return navigationState;
  1102. }
  1103. });
  1104. }
  1105. /**
  1106. * Registers a view provider that is queried for a view when no other view
  1107. * matches the navigation state. An error view provider should match any
  1108. * navigation state, but could return different views for different states.
  1109. * Its <code>getViewName(String navigationState)</code> should return
  1110. * <code>navigationState</code>.
  1111. *
  1112. * @param provider
  1113. */
  1114. public void setErrorProvider(ViewProvider provider) {
  1115. errorProvider = provider;
  1116. }
  1117. /**
  1118. * Listen to changes of the active view.
  1119. * <p>
  1120. * Registered listeners are invoked in registration order before (
  1121. * {@link ViewChangeListener#beforeViewChange(ViewChangeEvent)
  1122. * beforeViewChange()}) and after (
  1123. * {@link ViewChangeListener#afterViewChange(ViewChangeEvent)
  1124. * afterViewChange()}) a view change occurs.
  1125. *
  1126. * @param listener
  1127. * Listener to invoke during a view change.
  1128. * @since 8.0
  1129. */
  1130. public Registration addViewChangeListener(ViewChangeListener listener) {
  1131. listeners.add(listener);
  1132. return () -> listeners.remove(listener);
  1133. }
  1134. /**
  1135. * Removes a view change listener.
  1136. *
  1137. * @param listener
  1138. * Listener to remove.
  1139. * @deprecated use a {@link Registration} object returned by
  1140. * {@link #addViewChangeListener(ViewChangeListener)} to remove
  1141. * a listener
  1142. */
  1143. @Deprecated
  1144. public void removeViewChangeListener(ViewChangeListener listener) {
  1145. listeners.remove(listener);
  1146. }
  1147. /**
  1148. * Get view provider that handles the given {@code state}.
  1149. *
  1150. * @param state
  1151. * state string
  1152. * @return suitable provider
  1153. */
  1154. protected ViewProvider getViewProvider(String state) {
  1155. String longestViewName = null;
  1156. ViewProvider longestViewNameProvider = null;
  1157. for (ViewProvider provider : providers) {
  1158. String viewName = provider.getViewName(state);
  1159. if (null != viewName && (longestViewName == null
  1160. || viewName.length() > longestViewName.length())) {
  1161. longestViewName = viewName;
  1162. longestViewNameProvider = provider;
  1163. }
  1164. }
  1165. return longestViewNameProvider;
  1166. }
  1167. /**
  1168. * Creates view change event for given {@code view}, {@code viewName} and
  1169. * {@code parameters}.
  1170. *
  1171. * @since 7.6.7
  1172. */
  1173. public void destroy() {
  1174. stateManager.setNavigator(null);
  1175. ui.setNavigator(null);
  1176. }
  1177. /**
  1178. * Returns the current navigation state for which the
  1179. * {@link #getCurrentView()} has been constructed. This may differ to
  1180. * {@link #getState()} in case the URL has been changed on the browser and
  1181. * the navigator wasn't yet given an opportunity to construct new view. The
  1182. * state is in the form of
  1183. * <code>current-view-name/optional/parameters</code>
  1184. *
  1185. * @return the current navigation state, may be {@code null}.
  1186. */
  1187. public String getCurrentNavigationState() {
  1188. return currentNavigationState;
  1189. }
  1190. }