Search in sources :

Example 6 with NavigationEvent

use of com.vaadin.flow.router.NavigationEvent in project flow by vaadin.

the class AbstractNavigationStateRenderer method getRouteTarget.

/**
 * Gets the component instance to use for the given type and the
 * corresponding navigation event.
 * <p>
 * Override this method to control the creation of view instances.
 * <p>
 * By default always creates new instances.
 *
 * @param <T>
 *            the route target type
 * @param routeTargetType
 *            the class of the route target component
 * @param event
 *            the navigation event that uses the route target
 * @return an instance of the route target component
 */
@SuppressWarnings("unchecked")
static <// Non-private for testing purposes
T extends HasElement> T getRouteTarget(Class<T> routeTargetType, NavigationEvent event) {
    UI ui = event.getUI();
    Optional<HasElement> currentInstance = ui.getInternals().getActiveRouterTargetsChain().stream().filter(component -> component.getClass().equals(routeTargetType)).findAny();
    return (T) currentInstance.orElseGet(() -> Instantiator.get(ui).createRouteTarget(routeTargetType, event));
}
Also used : BeforeLeaveEvent(com.vaadin.flow.router.BeforeLeaveEvent) BeforeEnterEvent(com.vaadin.flow.router.BeforeEnterEvent) Component(com.vaadin.flow.component.Component) HashMap(java.util.HashMap) PageTitle(com.vaadin.flow.router.PageTitle) Deque(java.util.Deque) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) BeforeEvent(com.vaadin.flow.router.BeforeEvent) Router(com.vaadin.flow.router.Router) ArrayList(java.util.ArrayList) ExtendedClientDetails(com.vaadin.flow.component.page.ExtendedClientDetails) HashSet(java.util.HashSet) JsonValue(elemental.json.JsonValue) Element(com.vaadin.flow.dom.Element) ErrorParameter(com.vaadin.flow.router.ErrorParameter) Location(com.vaadin.flow.router.Location) LocationChangeEvent(com.vaadin.flow.router.LocationChangeEvent) ContinueNavigationAction(com.vaadin.flow.router.BeforeLeaveEvent.ContinueNavigationAction) ErrorNavigationEvent(com.vaadin.flow.router.ErrorNavigationEvent) UI(com.vaadin.flow.component.UI) NotFoundException(com.vaadin.flow.router.NotFoundException) BeforeEnterObserver(com.vaadin.flow.router.BeforeEnterObserver) NavigationTrigger(com.vaadin.flow.router.NavigationTrigger) VaadinSession(com.vaadin.flow.server.VaadinSession) Instantiator(com.vaadin.flow.di.Instantiator) RouterLayout(com.vaadin.flow.router.RouterLayout) NavigationHandler(com.vaadin.flow.router.NavigationHandler) HasElement(com.vaadin.flow.component.HasElement) Pair(com.vaadin.flow.internal.Pair) Collection(java.util.Collection) EventUtil(com.vaadin.flow.router.EventUtil) HttpServletResponse(javax.servlet.http.HttpServletResponse) Set(java.util.Set) ReflectTools(com.vaadin.flow.internal.ReflectTools) List(java.util.List) AfterNavigationEvent(com.vaadin.flow.router.AfterNavigationEvent) HasDynamicTitle(com.vaadin.flow.router.HasDynamicTitle) PreserveOnRefresh(com.vaadin.flow.router.PreserveOnRefresh) Optional(java.util.Optional) NavigationState(com.vaadin.flow.router.NavigationState) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) NavigationEvent(com.vaadin.flow.router.NavigationEvent) BeforeLeaveObserver(com.vaadin.flow.router.BeforeLeaveObserver) RouteParameters(com.vaadin.flow.router.RouteParameters) UI(com.vaadin.flow.component.UI) HasElement(com.vaadin.flow.component.HasElement)

Example 7 with NavigationEvent

use of com.vaadin.flow.router.NavigationEvent in project flow by vaadin.

the class BootstrapUtils method createInitialPageSettingsObject.

private static InitialPageSettings createInitialPageSettingsObject(BootstrapHandler.BootstrapContext context) {
    UI ui = context.getUI();
    WebBrowser browser = context.getSession().getBrowser();
    Router router = ui.getInternals().getRouter();
    NavigationEvent navigationEvent = new NavigationEvent(router, context.getRoute(), ui, NavigationTrigger.PAGE_LOAD);
    List<HasElement> components = ui.getChildren().map(component -> (HasElement) component).collect(Collectors.toList());
    AfterNavigationEvent afterNavigationEvent = new AfterNavigationEvent(new LocationChangeEvent(navigationEvent.getSource(), navigationEvent.getUI(), navigationEvent.getTrigger(), navigationEvent.getLocation(), components));
    return new InitialPageSettings(context.getRequest(), ui, afterNavigationEvent, browser);
}
Also used : Inline(com.vaadin.flow.component.page.Inline) URL(java.net.URL) HashMap(java.util.HashMap) Router(com.vaadin.flow.router.Router) Route(com.vaadin.flow.router.Route) Map(java.util.Map) Location(com.vaadin.flow.router.Location) LocationChangeEvent(com.vaadin.flow.router.LocationChangeEvent) Lookup(com.vaadin.flow.di.Lookup) UI(com.vaadin.flow.component.UI) NavigationTrigger(com.vaadin.flow.router.NavigationTrigger) QueryParameters(com.vaadin.flow.router.QueryParameters) RouterLayout(com.vaadin.flow.router.RouterLayout) HasElement(com.vaadin.flow.component.HasElement) Meta(com.vaadin.flow.component.page.Meta) IOException(java.io.IOException) ResourceProvider(com.vaadin.flow.di.ResourceProvider) RouteUtil(com.vaadin.flow.router.internal.RouteUtil) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) AfterNavigationEvent(com.vaadin.flow.router.AfterNavigationEvent) BodySize(com.vaadin.flow.component.page.BodySize) Optional(java.util.Optional) NavigationState(com.vaadin.flow.router.NavigationState) BufferedReader(java.io.BufferedReader) Viewport(com.vaadin.flow.component.page.Viewport) NavigationEvent(com.vaadin.flow.router.NavigationEvent) ParentLayout(com.vaadin.flow.router.ParentLayout) InputStream(java.io.InputStream) AfterNavigationEvent(com.vaadin.flow.router.AfterNavigationEvent) NavigationEvent(com.vaadin.flow.router.NavigationEvent) UI(com.vaadin.flow.component.UI) LocationChangeEvent(com.vaadin.flow.router.LocationChangeEvent) Router(com.vaadin.flow.router.Router) HasElement(com.vaadin.flow.component.HasElement) AfterNavigationEvent(com.vaadin.flow.router.AfterNavigationEvent)

Example 8 with NavigationEvent

use of com.vaadin.flow.router.NavigationEvent in project flow by vaadin.

the class NavigationStateRendererTest method handle_variousInputs_checkPushStateShouldBeCalledOrNot.

@Test
public // - navigation trigger is PAGE_LOAD, HISTORY, or PROGRAMMATIC
void handle_variousInputs_checkPushStateShouldBeCalledOrNot() {
    // given a service with instantiator
    MockVaadinServletService service = createMockServiceWithInstantiator();
    // given a locked session
    MockVaadinSession session = new AlwaysLockedVaadinSession(service);
    session.setConfiguration(new MockDeploymentConfiguration());
    // given a NavigationStateRenderer mapping to RegularView
    new NavigationStateBuilder(router).withTarget(RegularView.class).build();
    NavigationStateRenderer renderer = new NavigationStateRenderer(navigationStateFromTarget(RegularView.class));
    // given a UI with an instrumented Page that records
    // getHistory().pushState calls
    AtomicBoolean pushStateCalled = new AtomicBoolean(false);
    List<Location> pushStateLocations = new ArrayList<>();
    MockUI ui = new MockUI(session) {

        final Page page = new Page(this) {

            final History history = new History(getUI().get()) {

                @Override
                public void pushState(JsonValue state, Location location) {
                    pushStateCalled.set(true);
                    pushStateLocations.add(location);
                }
            };

            @Override
            public History getHistory() {
                return history;
            }
        };

        @Override
        public Page getPage() {
            return page;
        }
    };
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui, NavigationTrigger.UI_NAVIGATE, null, true));
    Assert.assertFalse("No pushState invocation is expected when forwardTo is true.", pushStateCalled.get());
    ui.getInternals().clearLastHandledNavigation();
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui, NavigationTrigger.PROGRAMMATIC));
    Assert.assertFalse("No pushState invocation is expected when navigation trigger is PROGRAMMATIC.", pushStateCalled.get());
    ui.getInternals().clearLastHandledNavigation();
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui, NavigationTrigger.HISTORY));
    Assert.assertFalse("No pushState invocation is expected when navigation trigger is HISTORY.", pushStateCalled.get());
    ui.getInternals().clearLastHandledNavigation();
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui, NavigationTrigger.PAGE_LOAD));
    Assert.assertFalse("No pushState invocation is expected when navigation trigger is PAGE_LOAD.", pushStateCalled.get());
    pushStateCalled.set(false);
    pushStateLocations.clear();
    ui.getInternals().clearLastHandledNavigation();
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui, NavigationTrigger.UI_NAVIGATE));
    Assert.assertTrue("pushState invocation is expected.", pushStateCalled.get());
    Assert.assertTrue(pushStateLocations.stream().anyMatch(location -> location.getPath().equals("regular")));
    pushStateCalled.set(false);
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui, NavigationTrigger.UI_NAVIGATE));
    Assert.assertFalse("No pushState invocation is expected when navigating to the current location.", pushStateCalled.get());
}
Also used : Arrays(java.util.Arrays) Component(com.vaadin.flow.component.Component) Json(elemental.json.Json) Router(com.vaadin.flow.router.Router) ExtendedClientDetails(com.vaadin.flow.component.page.ExtendedClientDetails) Route(com.vaadin.flow.router.Route) History(com.vaadin.flow.component.page.History) PendingJavaScriptResult(com.vaadin.flow.component.page.PendingJavaScriptResult) JsonValue(elemental.json.JsonValue) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Element(com.vaadin.flow.dom.Element) MockUI(com.vaadin.tests.util.MockUI) UI(com.vaadin.flow.component.UI) NavigationTrigger(com.vaadin.flow.router.NavigationTrigger) AlwaysLockedVaadinSession(com.vaadin.tests.util.AlwaysLockedVaadinSession) MockVaadinContext(com.vaadin.flow.server.MockVaadinContext) Set(java.util.Set) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) NotThreadSafe(net.jcip.annotations.NotThreadSafe) List(java.util.List) NavigationState(com.vaadin.flow.router.NavigationState) ServiceException(com.vaadin.flow.server.ServiceException) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestRouteRegistry(com.vaadin.flow.router.TestRouteRegistry) MockVaadinSession(com.vaadin.flow.server.MockVaadinSession) ArrayList(java.util.ArrayList) ApplicationRouteRegistry(com.vaadin.flow.server.startup.ApplicationRouteRegistry) Tag(com.vaadin.flow.component.Tag) Location(com.vaadin.flow.router.Location) MockInstantiator(com.vaadin.flow.server.MockInstantiator) ExpectedException(org.junit.rules.ExpectedException) Before(org.junit.Before) QueryParameters(com.vaadin.flow.router.QueryParameters) Text(com.vaadin.flow.component.Text) Page(com.vaadin.flow.component.page.Page) RouterLayout(com.vaadin.flow.router.RouterLayout) HasElement(com.vaadin.flow.component.HasElement) RouteRegistry(com.vaadin.flow.server.RouteRegistry) Test(org.junit.Test) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) NavigationStateBuilder(com.vaadin.flow.router.NavigationStateBuilder) RouteConfiguration(com.vaadin.flow.router.RouteConfiguration) PreserveOnRefresh(com.vaadin.flow.router.PreserveOnRefresh) JsonObject(elemental.json.JsonObject) Assert(org.junit.Assert) Collections(java.util.Collections) NavigationEvent(com.vaadin.flow.router.NavigationEvent) ParentLayout(com.vaadin.flow.router.ParentLayout) NavigationEvent(com.vaadin.flow.router.NavigationEvent) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) ArrayList(java.util.ArrayList) JsonValue(elemental.json.JsonValue) Router(com.vaadin.flow.router.Router) Page(com.vaadin.flow.component.page.Page) History(com.vaadin.flow.component.page.History) TestRouteRegistry(com.vaadin.flow.router.TestRouteRegistry) NavigationStateBuilder(com.vaadin.flow.router.NavigationStateBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockUI(com.vaadin.tests.util.MockUI) MockVaadinSession(com.vaadin.flow.server.MockVaadinSession) AlwaysLockedVaadinSession(com.vaadin.tests.util.AlwaysLockedVaadinSession) Location(com.vaadin.flow.router.Location) Test(org.junit.Test)

Example 9 with NavigationEvent

use of com.vaadin.flow.router.NavigationEvent in project flow by vaadin.

the class NavigationStateRendererTest method handle_preserveOnRefreshAndWindowNameKnown_componentIsCachedRetrievedAndFlushed.

@Test
public void handle_preserveOnRefreshAndWindowNameKnown_componentIsCachedRetrievedAndFlushed() {
    // given a service with instantiator
    MockVaadinServletService service = createMockServiceWithInstantiator();
    // given a locked session
    MockVaadinSession session = new AlwaysLockedVaadinSession(service);
    session.setConfiguration(new MockDeploymentConfiguration());
    // given a UI that contain a window name ROOT.123
    MockUI ui1 = new MockUI(session);
    ExtendedClientDetails details = Mockito.mock(ExtendedClientDetails.class);
    Mockito.when(details.getWindowName()).thenReturn("ROOT.123");
    ui1.getInternals().setExtendedClientDetails(details);
    // given a NavigationStateRenderer mapping to PreservedView
    NavigationStateRenderer renderer1 = new NavigationStateRenderer(navigationStateFromTarget(PreservedView.class));
    // when a navigation event reaches the renderer
    renderer1.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("preserved"), ui1, NavigationTrigger.PAGE_LOAD));
    // then the session has a cached record of the view
    Assert.assertTrue("Session expected to have cached view", AbstractNavigationStateRenderer.getPreservedChain(session, "ROOT.123", new Location("preserved")).isPresent());
    // given the recently instantiated view
    final Component view = (Component) ui1.getInternals().getActiveRouterTargetsChain().get(0);
    // given a new UI with the same window name
    MockUI ui2 = new MockUI(session);
    ui2.getInternals().setExtendedClientDetails(details);
    // given a new NavigationStateRenderer mapping to PreservedView
    NavigationStateRenderer renderer2 = new NavigationStateRenderer(navigationStateFromTarget(PreservedView.class));
    // when another navigation targets the same location
    renderer2.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("preserved"), ui2, NavigationTrigger.PAGE_LOAD));
    // then the same view is routed to
    Assert.assertEquals("Expected same view", view, ui1.getInternals().getActiveRouterTargetsChain().get(0));
    // given yet another new UI with the same window name
    MockUI ui3 = new MockUI(session);
    ui3.getInternals().setExtendedClientDetails(details);
    // given a new NavigationStateRenderer mapping to another location
    NavigationStateRenderer renderer3 = new NavigationStateRenderer(navigationStateFromTarget(RegularView.class));
    // when a navigation event targets that other location
    renderer3.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("regular"), ui2, NavigationTrigger.PAGE_LOAD));
    // then session no longer has a cached record at location "preserved"
    Assert.assertFalse("Session expected to not have cached view", AbstractNavigationStateRenderer.hasPreservedChainOfLocation(session, new Location("preserved")));
}
Also used : NavigationEvent(com.vaadin.flow.router.NavigationEvent) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) Router(com.vaadin.flow.router.Router) TestRouteRegistry(com.vaadin.flow.router.TestRouteRegistry) MockUI(com.vaadin.tests.util.MockUI) MockVaadinSession(com.vaadin.flow.server.MockVaadinSession) AlwaysLockedVaadinSession(com.vaadin.tests.util.AlwaysLockedVaadinSession) ExtendedClientDetails(com.vaadin.flow.component.page.ExtendedClientDetails) Component(com.vaadin.flow.component.Component) Location(com.vaadin.flow.router.Location) Test(org.junit.Test)

Example 10 with NavigationEvent

use of com.vaadin.flow.router.NavigationEvent in project flow by vaadin.

the class NavigationStateRendererTest method handle_preserveOnRefresh_sameUI_uiIsNotClosed_childrenAreNotRemoved.

@Test
public void handle_preserveOnRefresh_sameUI_uiIsNotClosed_childrenAreNotRemoved() {
    // given a service with instantiator
    MockVaadinServletService service = createMockServiceWithInstantiator();
    // the path is the same, location params will be different
    String path = "foo";
    // given a locked session
    MockVaadinSession session = new AlwaysLockedVaadinSession(service);
    session.setConfiguration(new MockDeploymentConfiguration());
    // given a NavigationStateRenderer mapping to PreservedView
    NavigationStateRenderer renderer = new NavigationStateRenderer(navigationStateFromTarget(PreservedView.class));
    // given the session has a cache of PreservedView at this location
    final PreservedView view = new PreservedView();
    MockUI ui = new MockUI(session);
    ui.add(view);
    AbstractNavigationStateRenderer.setPreservedChain(session, "ROOT.123", new Location(path, new QueryParameters(Collections.singletonMap("a", Collections.emptyList()))), new ArrayList<>(Arrays.asList(view)));
    ExtendedClientDetails details = Mockito.mock(ExtendedClientDetails.class);
    Mockito.when(details.getWindowName()).thenReturn("ROOT.123");
    ui.getInternals().setExtendedClientDetails(details);
    AtomicInteger count = new AtomicInteger();
    view.addDetachListener(event -> count.getAndIncrement());
    NavigationEvent event = new NavigationEvent(new Router(new TestRouteRegistry()), new Location(path, new QueryParameters(Collections.singletonMap("b", Collections.emptyList()))), ui, NavigationTrigger.ROUTER_LINK, Json.createObject(), false);
    renderer.handle(event);
    Assert.assertFalse(ui.isClosing());
    Assert.assertEquals(0, count.get());
}
Also used : NavigationEvent(com.vaadin.flow.router.NavigationEvent) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) Router(com.vaadin.flow.router.Router) QueryParameters(com.vaadin.flow.router.QueryParameters) TestRouteRegistry(com.vaadin.flow.router.TestRouteRegistry) MockUI(com.vaadin.tests.util.MockUI) MockVaadinSession(com.vaadin.flow.server.MockVaadinSession) AlwaysLockedVaadinSession(com.vaadin.tests.util.AlwaysLockedVaadinSession) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExtendedClientDetails(com.vaadin.flow.component.page.ExtendedClientDetails) Location(com.vaadin.flow.router.Location) Test(org.junit.Test)

Aggregations

NavigationEvent (com.vaadin.flow.router.NavigationEvent)25 Location (com.vaadin.flow.router.Location)19 Test (org.junit.Test)15 Router (com.vaadin.flow.router.Router)11 UI (com.vaadin.flow.component.UI)10 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)10 MockUI (com.vaadin.tests.util.MockUI)10 MockVaadinSession (com.vaadin.flow.server.MockVaadinSession)9 AlwaysLockedVaadinSession (com.vaadin.tests.util.AlwaysLockedVaadinSession)8 ExtendedClientDetails (com.vaadin.flow.component.page.ExtendedClientDetails)7 TestRouteRegistry (com.vaadin.flow.router.TestRouteRegistry)7 MockDeploymentConfiguration (com.vaadin.tests.util.MockDeploymentConfiguration)7 Component (com.vaadin.flow.component.Component)6 ErrorNavigationEvent (com.vaadin.flow.router.ErrorNavigationEvent)6 HasElement (com.vaadin.flow.component.HasElement)5 AfterNavigationEvent (com.vaadin.flow.router.AfterNavigationEvent)5 NavigationState (com.vaadin.flow.router.NavigationState)5 NavigationStateBuilder (com.vaadin.flow.router.NavigationStateBuilder)5 Page (com.vaadin.flow.component.page.Page)4 Element (com.vaadin.flow.dom.Element)4