Search in sources :

Example 6 with Page

use of com.vaadin.flow.component.page.Page in project flow by vaadin.

the class NavigationStateRendererTest method handle_RouterLinkTrigger_scrollPositionHandlerAfterServerNavigationIsInvoked.

@Test
public void handle_RouterLinkTrigger_scrollPositionHandlerAfterServerNavigationIsInvoked() {
    // 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 JS invocations
    AtomicBoolean jsInvoked = new AtomicBoolean(false);
    List<String> jsExpressions = new ArrayList<>();
    MockUI ui = new MockUI(session) {

        final Page page = new Page(this) {

            @Override
            public PendingJavaScriptResult executeJs(String expression, Serializable... params) {
                jsInvoked.set(true);
                jsExpressions.add(expression);
                return super.executeJs(expression, params);
            }
        };

        @Override
        public Page getPage() {
            return page;
        }
    };
    JsonObject state = Json.createObject();
    state.put("href", "view/regular");
    state.put("scrollPositionX", 0.0);
    state.put("scrollPositionY", 0.0);
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("preserved"), ui, NavigationTrigger.ROUTER_LINK, state, false));
    // then client-side JS was invoked
    Assert.assertTrue("Expected JS invocation", jsInvoked.get());
    Assert.assertTrue(jsExpressions.stream().anyMatch(expression -> expression.contains("scrollPositionHandlerAfterServerNavigation")));
}
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) Serializable(java.io.Serializable) PendingJavaScriptResult(com.vaadin.flow.component.page.PendingJavaScriptResult) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) ArrayList(java.util.ArrayList) JsonObject(elemental.json.JsonObject) Router(com.vaadin.flow.router.Router) Page(com.vaadin.flow.component.page.Page) 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 7 with Page

use of com.vaadin.flow.component.page.Page in project flow by vaadin.

the class NavigationStateRendererTest method handle_preserveOnRefreshAndWindowNameNotKnown_clientSideCallTriggered.

@Test
public void handle_preserveOnRefreshAndWindowNameNotKnown_clientSideCallTriggered() {
    // given a service with instantiator
    MockVaadinServletService service = createMockServiceWithInstantiator();
    // given a locked session
    MockVaadinSession session = new AlwaysLockedVaadinSession(service);
    // given a NavigationStateRenderer mapping to PreservedView
    NavigationStateRenderer renderer = new NavigationStateRenderer(navigationStateFromTarget(PreservedView.class));
    // given the session has a cache of something at this location
    AbstractNavigationStateRenderer.setPreservedChain(session, "", new Location("preserved"), new ArrayList<>(Arrays.asList(Mockito.mock(Component.class))));
    // given a UI that contain no window name with an instrumented Page
    // that records JS invocations
    AtomicBoolean jsInvoked = new AtomicBoolean(false);
    MockUI ui = new MockUI(session) {

        final Page page = new Page(this) {

            @Override
            public PendingJavaScriptResult executeJs(String expression, Serializable... params) {
                jsInvoked.set(true);
                return super.executeJs(expression, params);
            }
        };

        @Override
        public Page getPage() {
            return page;
        }
    };
    // when a navigation event reaches the renderer
    renderer.handle(new NavigationEvent(new Router(new TestRouteRegistry()), new Location("preserved"), ui, NavigationTrigger.PAGE_LOAD));
    // then client-side JS was invoked
    Assert.assertTrue("Expected JS invocation", jsInvoked.get());
}
Also used : NavigationEvent(com.vaadin.flow.router.NavigationEvent) Serializable(java.io.Serializable) PendingJavaScriptResult(com.vaadin.flow.component.page.PendingJavaScriptResult) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) Router(com.vaadin.flow.router.Router) Page(com.vaadin.flow.component.page.Page) TestRouteRegistry(com.vaadin.flow.router.TestRouteRegistry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockUI(com.vaadin.tests.util.MockUI) MockVaadinSession(com.vaadin.flow.server.MockVaadinSession) AlwaysLockedVaadinSession(com.vaadin.tests.util.AlwaysLockedVaadinSession) Component(com.vaadin.flow.component.Component) Location(com.vaadin.flow.router.Location) Test(org.junit.Test)

Example 8 with Page

use of com.vaadin.flow.component.page.Page in project flow by vaadin.

the class FragmentLinkView method onAttach.

@Override
protected void onAttach(AttachEvent attachEvent) {
    Page page = attachEvent.getUI().getPage();
    page.executeJs("var i = 0;" + "window.addEventListener('hashchange', function(event) {" + "var x = document.createElement('span');" + "x.textContent = ' ' + i;" + "i++;" + "x.class = 'hashchange';" + "document.getElementById('placeholder').appendChild(x);}," + " false);");
    HistoryStateChangeHandler current = page.getHistory().getHistoryStateChangeHandler();
    page.getHistory().setHistoryStateChangeHandler(event -> {
        if (event.getLocation().getPath().equals("override")) {
            event.getSource().replaceState(null, "overridden#Scroll_Target2");
        } else {
            current.onHistoryStateChange(event);
        }
    });
}
Also used : HistoryStateChangeHandler(com.vaadin.flow.component.page.History.HistoryStateChangeHandler) Page(com.vaadin.flow.component.page.Page)

Example 9 with Page

use of com.vaadin.flow.component.page.Page in project flow by vaadin.

the class ViewAccessCheckerTest method setupRequest.

private Result setupRequest(Class navigationTarget, User user, boolean productionMode) {
    CurrentInstance.clearAll();
    Principal principal;
    String[] roles;
    if (user == User.USER_NO_ROLES) {
        principal = AccessAnnotationCheckerTest.USER_PRINCIPAL;
        roles = new String[0];
    } else if (user == User.NORMAL_USER) {
        principal = AccessAnnotationCheckerTest.USER_PRINCIPAL;
        roles = new String[] { "user" };
    } else if (user == User.ADMIN) {
        principal = AccessAnnotationCheckerTest.USER_PRINCIPAL;
        roles = new String[] { "admin" };
    } else {
        principal = null;
        roles = new String[0];
    }
    VaadinServletRequest vaadinServletRequest = Mockito.mock(VaadinServletRequest.class);
    HttpServletRequest httpServletRequest = AccessAnnotationCheckerTest.createRequest(principal, roles);
    Mockito.when(vaadinServletRequest.getHttpServletRequest()).thenReturn(httpServletRequest);
    CurrentInstance.set(VaadinRequest.class, vaadinServletRequest);
    Router router = Mockito.mock(Router.class);
    UI ui = Mockito.mock(UI.class);
    Page page = Mockito.mock(Page.class);
    Mockito.when(ui.getPage()).thenReturn(page);
    VaadinSession vaadinSession = Mockito.mock(VaadinSession.class);
    Mockito.when(ui.getSession()).thenReturn(vaadinSession);
    DeploymentConfiguration configuration = Mockito.mock(DeploymentConfiguration.class);
    Mockito.when(vaadinSession.getConfiguration()).thenReturn(configuration);
    Mockito.when(configuration.isProductionMode()).thenReturn(productionMode);
    UIInternals uiInternals = Mockito.mock(UIInternals.class);
    Mockito.when(ui.getInternals()).thenReturn(uiInternals);
    Mockito.when(uiInternals.getRouter()).thenReturn(router);
    Mockito.when(router.getErrorNavigationTarget(Mockito.any())).thenAnswer(invocation -> {
        Class<?> exceptionClass = invocation.getArguments()[0].getClass();
        if (exceptionClass == NotFoundException.class) {
            return Optional.of(new ErrorTargetEntry(RouteNotFoundError.class, NotFoundException.class));
        } else {
            return Optional.empty();
        }
    });
    Location location = new Location(getRoute(navigationTarget));
    NavigationEvent navigationEvent = new NavigationEvent(router, location, ui, NavigationTrigger.ROUTER_LINK);
    BeforeEnterEvent event = new BeforeEnterEvent(navigationEvent, navigationTarget, new ArrayList<>());
    RouteRegistry routeRegistry = Mockito.mock(RouteRegistry.class);
    Mockito.when(router.getRegistry()).thenReturn(routeRegistry);
    Mockito.when(routeRegistry.getNavigationTarget(Mockito.anyString())).thenAnswer(invocation -> {
        String url = (String) invocation.getArguments()[0];
        if (location.getPath().equals(url)) {
            return Optional.of(navigationTarget);
        } else {
            return Optional.empty();
        }
    });
    HttpSession session = Mockito.mock(HttpSession.class);
    Map<String, Object> sessionAttributes = new HashMap<>();
    Mockito.when(httpServletRequest.getSession()).thenReturn(session);
    Mockito.doAnswer(invocation -> {
        String key = (String) invocation.getArguments()[0];
        Object value = invocation.getArguments()[1];
        sessionAttributes.put(key, value);
        return null;
    }).when(session).setAttribute(Mockito.anyString(), Mockito.any());
    Result info = new Result();
    info.event = event;
    info.sessionAttributes = sessionAttributes;
    Mockito.doAnswer(invocation -> {
        info.redirectUsingPageLocation = (String) invocation.getArguments()[0];
        return null;
    }).when(page).setLocation(Mockito.anyString());
    return info;
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) RouteRegistry(com.vaadin.flow.server.RouteRegistry) HashMap(java.util.HashMap) NotFoundException(com.vaadin.flow.router.NotFoundException) Page(com.vaadin.flow.component.page.Page) HttpServletRequest(javax.servlet.http.HttpServletRequest) UI(com.vaadin.flow.component.UI) NavigationEvent(com.vaadin.flow.router.NavigationEvent) HttpSession(javax.servlet.http.HttpSession) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) Router(com.vaadin.flow.router.Router) UIInternals(com.vaadin.flow.component.internal.UIInternals) BeforeEnterEvent(com.vaadin.flow.router.BeforeEnterEvent) ErrorTargetEntry(com.vaadin.flow.router.internal.ErrorTargetEntry) RouteNotFoundError(com.vaadin.flow.router.RouteNotFoundError) Principal(java.security.Principal) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) Location(com.vaadin.flow.router.Location)

Example 10 with Page

use of com.vaadin.flow.component.page.Page in project flow by vaadin.

the class JavaScriptBootstrapUITest method mockPage.

private Page mockPage() {
    Page page = Mockito.mock(Page.class);
    Mockito.when(ui.getPage()).thenReturn(page);
    History history = new History(ui);
    Mockito.when(page.getHistory()).thenReturn(history);
    return page;
}
Also used : Page(com.vaadin.flow.component.page.Page) History(com.vaadin.flow.component.page.History)

Aggregations

Page (com.vaadin.flow.component.page.Page)13 Location (com.vaadin.flow.router.Location)7 Test (org.junit.Test)7 UI (com.vaadin.flow.component.UI)5 Router (com.vaadin.flow.router.Router)5 Serializable (java.io.Serializable)5 Component (com.vaadin.flow.component.Component)4 NavigationEvent (com.vaadin.flow.router.NavigationEvent)4 HasElement (com.vaadin.flow.component.HasElement)3 ExtendedClientDetails (com.vaadin.flow.component.page.ExtendedClientDetails)3 History (com.vaadin.flow.component.page.History)3 PendingJavaScriptResult (com.vaadin.flow.component.page.PendingJavaScriptResult)3 RouterLayout (com.vaadin.flow.router.RouterLayout)3 TestRouteRegistry (com.vaadin.flow.router.TestRouteRegistry)3 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)3 MockVaadinSession (com.vaadin.flow.server.MockVaadinSession)3 RouteRegistry (com.vaadin.flow.server.RouteRegistry)3 AlwaysLockedVaadinSession (com.vaadin.tests.util.AlwaysLockedVaadinSession)3 MockUI (com.vaadin.tests.util.MockUI)3 ArrayList (java.util.ArrayList)3