diff --git a/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/LayoutScopedPlainView.java b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/LayoutScopedPlainView.java new file mode 100644 index 00000000..aadaaee9 --- /dev/null +++ b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/LayoutScopedPlainView.java @@ -0,0 +1,49 @@ +/* + * Copyright 2000-2021 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.cdi.itest.routecontext; + +import jakarta.annotation.PostConstruct; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; + +import com.vaadin.cdi.annotation.CdiComponent; +import com.vaadin.cdi.annotation.RouteScopeOwner; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.NativeLabel; +import com.vaadin.flow.router.Route; + +/** + * A plain sibling of {@link LayoutScopedPreservedView} under the same layout. + * The layout instance is reused when navigating between the two, so the beans + * it owns must not be recreated. + */ +@Route(value = "layout-scoped-plain", layout = MainLayout.class) +@CdiComponent +public class LayoutScopedPlainView extends Div { + + public static final String LAYOUT_BEAN_LABEL = "plain-layout-bean"; + + @Inject + @RouteScopeOwner(MainLayout.class) + private Instance injection; + + @PostConstruct + private void init() { + NativeLabel beanLabel = new NativeLabel(injection.get().getData()); + beanLabel.setId(LAYOUT_BEAN_LABEL); + add(beanLabel); + } +} diff --git a/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/LayoutScopedPreservedView.java b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/LayoutScopedPreservedView.java new file mode 100644 index 00000000..b8a65eda --- /dev/null +++ b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/LayoutScopedPreservedView.java @@ -0,0 +1,56 @@ +/* + * Copyright 2000-2021 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.cdi.itest.routecontext; + +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; + +import com.vaadin.cdi.annotation.CdiComponent; +import com.vaadin.cdi.annotation.RouteScopeOwner; +import com.vaadin.flow.component.AttachEvent; +import com.vaadin.flow.component.html.Div; +import com.vaadin.flow.component.html.NativeLabel; +import com.vaadin.flow.router.PreserveOnRefresh; +import com.vaadin.flow.router.Route; + +/** + * A preserved child of {@link MainLayout}, which is not preserved itself. Flow + * preserves the whole chain, so the beans owned by the layout are shared with + * the UI created by a page refresh. + */ +@PreserveOnRefresh +@Route(value = "layout-scoped-preserved", layout = MainLayout.class) +@CdiComponent +public class LayoutScopedPreservedView extends Div { + + public static final String LAYOUT_BEAN_LABEL = "preserved-layout-bean"; + + @Inject + @RouteScopeOwner(MainLayout.class) + private Instance injection; + + private NativeLabel beanLabel; + + @Override + protected void onAttach(AttachEvent attachEvent) { + if (beanLabel != null) { + remove(beanLabel); + } + beanLabel = new NativeLabel(injection.get().getData()); + beanLabel.setId(LAYOUT_BEAN_LABEL); + add(beanLabel); + } +} diff --git a/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayout.java b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayout.java index d84c902f..946c7c0b 100644 --- a/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayout.java +++ b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayout.java @@ -29,6 +29,8 @@ public class MainLayout extends Div implements RouterLayout { public static final String INVALID = "invalid"; public static final String PARENT_NO_OWNER = "parent-no-owner"; public static final String CHILD_NO_OWNER = "child-no-owner"; + public static final String LAYOUT_PRESERVED = "layout-preserved"; + public static final String LAYOUT_PLAIN = "layout-plain"; private NativeLabel uiIdLabel; @@ -36,7 +38,10 @@ public MainLayout() { add(new RouterLink(PRESERVE, PreserveOnRefreshView.class), new RouterLink(INVALID, InvalidView.class), new RouterLink(PARENT_NO_OWNER, ParentNoOwnerView.class), - new RouterLink(CHILD_NO_OWNER, ChildNoOwnerView.class)); + new RouterLink(CHILD_NO_OWNER, ChildNoOwnerView.class), + new RouterLink(LAYOUT_PRESERVED, + LayoutScopedPreservedView.class), + new RouterLink(LAYOUT_PLAIN, LayoutScopedPlainView.class)); ; } diff --git a/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayoutBean.java b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayoutBean.java new file mode 100644 index 00000000..1f827d22 --- /dev/null +++ b/vaadin-cdi-itest/src/main/java/com/vaadin/cdi/itest/routecontext/MainLayoutBean.java @@ -0,0 +1,39 @@ +/* + * Copyright 2000-2021 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.cdi.itest.routecontext; + +import jakarta.annotation.PostConstruct; + +import java.util.UUID; + +import com.vaadin.cdi.annotation.CdiComponent; +import com.vaadin.cdi.annotation.RouteScopeOwner; +import com.vaadin.cdi.annotation.RouteScoped; + +/** + * A bean owned by the layout shared by a preserved and a plain child view. + */ +@RouteScoped +@RouteScopeOwner(MainLayout.class) +@CdiComponent +public class MainLayoutBean extends AbstractCountedBean { + + @PostConstruct + private void init() { + setData(UUID.randomUUID().toString()); + } + +} diff --git a/vaadin-cdi-itest/src/test/java/com/vaadin/cdi/itest/RouteContextTest.java b/vaadin-cdi-itest/src/test/java/com/vaadin/cdi/itest/RouteContextTest.java index 94c4f330..57df6325 100644 --- a/vaadin-cdi-itest/src/test/java/com/vaadin/cdi/itest/RouteContextTest.java +++ b/vaadin-cdi-itest/src/test/java/com/vaadin/cdi/itest/RouteContextTest.java @@ -24,6 +24,7 @@ import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; +import org.openqa.selenium.WindowType; import com.vaadin.cdi.itest.routecontext.ApartBean; import com.vaadin.cdi.itest.routecontext.AssignedBean; @@ -39,7 +40,10 @@ import com.vaadin.cdi.itest.routecontext.EventView; import com.vaadin.cdi.itest.routecontext.LayoutEventView; import com.vaadin.cdi.itest.routecontext.LayoutEventView2; +import com.vaadin.cdi.itest.routecontext.LayoutScopedPlainView; +import com.vaadin.cdi.itest.routecontext.LayoutScopedPreservedView; import com.vaadin.cdi.itest.routecontext.MainLayout; +import com.vaadin.cdi.itest.routecontext.MainLayoutBean; import com.vaadin.cdi.itest.routecontext.MasterView; import com.vaadin.cdi.itest.routecontext.PostponeView; import com.vaadin.cdi.itest.routecontext.PreserveOnRefreshBean; @@ -297,6 +301,76 @@ public void routeScopedBeanIsDestroyedOnNavigationOutOfViewAfterPreserveOnRefres assertDestroyed(PreserveOnRefreshBean.class, 1); } + @Test + public void noPreserveOnRefresh_routeTargetIsRecreatedOnRefresh() + throws IOException { + getDriver().get(getDriver().getCurrentUrl()); + + // UI ID has to be updated: all bean creations/removals will be done + // now within the new UI + uiId = getText(MainLayout.UIID); + + assertConstructed(RootView.class, 1); + assertDestroyed(RootView.class, 0); + assertRootViewIsRendered(); + } + + @Test + public void noPreserveOnRefresh_otherUIWithSameWindowName_routeTargetIsNotShared() + throws IOException { + String url = getDriver().getCurrentUrl(); + String windowName = (String) executeScript("return window.name;"); + + // Open a second tab and make it report the window name of the first + // one, as a duplicated tab or a restored browser session does. Both + // UIs are alive at the same time, so a route scope keyed by window + // name would be shared between them. + getDriver().switchTo().newWindow(WindowType.TAB); + getDriver().get(url); + executeScript("window.name = arguments[0];", windowName); + // same origin reload, so the window name is retained + getDriver().navigate().refresh(); + + uiId = getText(MainLayout.UIID); + + assertConstructed(RootView.class, 1); + assertDestroyed(RootView.class, 0); + assertRootViewIsRendered(); + } + + @Test + public void sharedLayout_navigateBetweenPreservedAndPlainChild_layoutBeanIsKept() + throws IOException { + follow(MainLayout.LAYOUT_PRESERVED); + String beanData = getText(LayoutScopedPreservedView.LAYOUT_BEAN_LABEL); + + assertConstructed(MainLayoutBean.class, 1); + assertDestroyed(MainLayoutBean.class, 0); + + // the layout instance is reused, so the beans it owns must not be + // recreated even if the navigation chain is not preserved anymore + follow(MainLayout.LAYOUT_PLAIN); + + Assert.assertEquals(beanData, + getText(LayoutScopedPlainView.LAYOUT_BEAN_LABEL)); + assertConstructed(MainLayoutBean.class, 1); + assertDestroyed(MainLayoutBean.class, 0); + + // ... and the other way around + follow(MainLayout.LAYOUT_PRESERVED); + + Assert.assertEquals(beanData, + getText(LayoutScopedPreservedView.LAYOUT_BEAN_LABEL)); + assertConstructed(MainLayoutBean.class, 1); + assertDestroyed(MainLayoutBean.class, 0); + } + + private void assertRootViewIsRendered() { + Assert.assertNotNull( + "The root view is expected to be rendered in the current UI", + findElement(By.linkText(RootView.MASTER))); + } + @Test public void preserveOnRefresh_beanIsNotDestroyed() throws IOException { follow(MainLayout.PRESERVE); diff --git a/vaadin-cdi/src/main/java/com/vaadin/cdi/context/RouteScopedContext.java b/vaadin-cdi/src/main/java/com/vaadin/cdi/context/RouteScopedContext.java index 1b7309e1..1df33526 100644 --- a/vaadin-cdi/src/main/java/com/vaadin/cdi/context/RouteScopedContext.java +++ b/vaadin-cdi/src/main/java/com/vaadin/cdi/context/RouteScopedContext.java @@ -41,6 +41,7 @@ import com.vaadin.flow.component.page.ExtendedClientDetails; import com.vaadin.flow.router.AfterNavigationEvent; import com.vaadin.flow.router.BeforeEnterEvent; +import com.vaadin.flow.router.PreserveOnRefresh; import com.vaadin.flow.router.RouterLayout; import com.vaadin.flow.server.VaadinSession; @@ -55,6 +56,17 @@ public class RouteScopedContext extends AbstractContext { public static class ContextualStorageManager extends AbstractContextualStorageManager { + /** + * Prefix of storage identifiers bound to a single UI instance. + */ + private static final String UI_STORE_ID_PREFIX = "uid-"; + + /** + * Prefix of storage identifiers bound to a browser window, and thus + * shared by all the UIs of that window. + */ + private static final String WINDOW_STORE_ID_PREFIX = "win-"; + public ContextualStorageManager() { // Session lock checked in VaadinSessionScopedContext while // getting the session attribute. @@ -92,10 +104,10 @@ private void onBeforeEnter(@Observes BeforeEnterEvent event) { private void destroyDescopedBeans(UI ui, Set> navigationChain) { - String uiStoreId = getUIStoreId(ui); + Set uiStoreIds = getUIStoreIds(ui); Set missingKeys = getKeySet().stream() - .filter(key -> key.getUIId().equals(uiStoreId)) + .filter(key -> uiStoreIds.contains(key.getUIId())) .filter(key -> !navigationChain.contains(key.getOwner())) .collect(Collectors.toSet()); @@ -103,6 +115,17 @@ private void destroyDescopedBeans(UI ui, } private void handleUIDetach(UI ui, RouteStorageKey key) { + if (getContextualStorage(key, false) == null) { + // The storage has been relocated to another key because the + // scope of its owner changed, or it is already destroyed. + return; + } + if (!key.isWindowScoped()) { + // The storage belongs to this UI only, so there is nothing to + // preserve for a potential UI created by a page refresh. + destroy(key); + return; + } UI uiAfterRefresh = findPreservingUI(ui); if (uiAfterRefresh == null) { destroy(key); @@ -131,36 +154,95 @@ private static String getWindowName(UI ui) { } private RouteStorageKey getKey(UI ui, Class owner) { - ExtendedClientDetails details = ui.getInternals() - .getExtendedClientDetails(); - RouteStorageKey key = new RouteStorageKey(owner, getUIStoreId(ui)); - if (details.getWindowName() == null) { - ui.getPage().retrieveExtendedClientDetails( - det -> relocate(ui, key)); + RouteStorageKey uiKey = new RouteStorageKey(owner, getUIStoreId(ui), + false); + String windowName = getWindowName(ui); + if (windowName == null) { + return uiKey; + } + RouteStorageKey windowKey = new RouteStorageKey(owner, + WINDOW_STORE_ID_PREFIX + windowName, true); + // Beans are shared with the UI created by a page refresh only if + // the navigation chain is preserved by Flow. In that case the + // storage is bound to the browser window, exactly like Flow binds + // the preserved component chain. + if (isPreserveOnRefreshChain(ui)) { + return rescope(uiKey, windowKey, ui); + } + // The owner may stay in the navigation chain while the chain stops + // being preserved, for example navigating from a preserved view to + // a plain sibling of the same layout. Its beans are then bound back + // to this UI, unless another UI of the same browser window is still + // alive and may be holding the preserved chain. + if (getContextualStorage(windowKey, false) != null + && findPreservingUI(ui) == null) { + return rescope(windowKey, uiKey, ui); } - return key; + return uiKey; } - private void relocate(UI ui, RouteStorageKey key) { - relocate(key, - new RouteStorageKey(key.getOwner(), getUIStoreId(ui))); + /** + * Moves the storage of an owner whose scope changed, so that its beans + * are not recreated while the owner stays in the navigation chain. + * + * @return the key the storage of the owner is bound to, always + * {@code to} + */ + private RouteStorageKey rescope(RouteStorageKey from, + RouteStorageKey to, UI ui) { + if (getContextualStorage(to, false) == null + && getContextualStorage(from, false) != null) { + relocate(from, to); + // The listener registered for the previous key does not find + // any storage anymore, so the new key needs its own. + ui.addDetachListener( + event -> handleUIDetach(event.getUI(), to)); + } + return to; } private List getActiveContextualStorages() { - return getKeySet().stream().filter( - key -> key.getUIId().equals(getUIStoreId(UI.getCurrent()))) + Set uiStoreIds = getUIStoreIds(UI.getCurrent()); + return getKeySet().stream() + .filter(key -> uiStoreIds.contains(key.getUIId())) .map(key -> getContextualStorage(key, false)) .collect(Collectors.toList()); } + /** + * Gets all the storage identifiers a UI can hold beans for: its own + * one, plus the one shared by all the UIs of the same browser window. A + * single UI may own both kinds of storage, for example after navigating + * from a regular view to a {@link PreserveOnRefresh} one. + */ + private Set getUIStoreIds(UI ui) { + Set ids = new HashSet<>(); + ids.add(getUIStoreId(ui)); + String windowName = getWindowName(ui); + if (windowName != null) { + ids.add(WINDOW_STORE_ID_PREFIX + windowName); + } + return ids; + } + private String getUIStoreId(UI ui) { - ExtendedClientDetails details = ui.getInternals() - .getExtendedClientDetails(); - if (details.getWindowName() == null) { - return "uid-" + ui.getUIId(); - } else { - return "win-" + getWindowName(ui); + return UI_STORE_ID_PREFIX + ui.getUIId(); + } + + private static boolean isPreserveOnRefreshChain(UI ui) { + NavigationData data = ComponentUtil.getData(ui, + NavigationData.class); + if (data == null) { + return false; } + return isPreserveOnRefresh(data.getNavigationTarget()) + || data.getLayouts().stream().anyMatch( + ContextualStorageManager::isPreserveOnRefresh); + } + + private static boolean isPreserveOnRefresh(Class clazz) { + return clazz != null + && clazz.isAnnotationPresent(PreserveOnRefresh.class); } } @@ -168,10 +250,14 @@ private String getUIStoreId(UI ui) { private static class RouteStorageKey implements Serializable { private final Class owner; private final String uiId; + // Derived from uiId, so it is not part of equals/hashCode + private final boolean windowScoped; - private RouteStorageKey(Class owner, String uiId) { + private RouteStorageKey(Class owner, String uiId, + boolean windowScoped) { this.owner = owner; this.uiId = uiId; + this.windowScoped = windowScoped; } @Override @@ -204,6 +290,15 @@ String getUIId() { return uiId; } + /** + * Whether the storage is shared by all the UIs of the same browser + * window, as required to preserve beans of a {@link PreserveOnRefresh} + * navigation chain. + */ + boolean isWindowScoped() { + return windowScoped; + } + } static class NavigationData implements Serializable { diff --git a/vaadin-cdi/src/test/java/com/vaadin/cdi/context/RouteContextualStorageManagerTest.java b/vaadin-cdi/src/test/java/com/vaadin/cdi/context/RouteContextualStorageManagerTest.java index 7634a69c..f4feef5e 100644 --- a/vaadin-cdi/src/test/java/com/vaadin/cdi/context/RouteContextualStorageManagerTest.java +++ b/vaadin-cdi/src/test/java/com/vaadin/cdi/context/RouteContextualStorageManagerTest.java @@ -45,7 +45,9 @@ import com.vaadin.flow.router.AfterNavigationEvent; import com.vaadin.flow.router.BeforeEnterEvent; import com.vaadin.flow.router.LocationChangeEvent; +import com.vaadin.flow.router.PreserveOnRefresh; import com.vaadin.flow.router.Route; +import com.vaadin.flow.router.RouterLayout; import com.vaadin.flow.server.VaadinSession; public class RouteContextualStorageManagerTest extends AbstractWeldTest { @@ -92,6 +94,49 @@ private void onDestroy() { public static class Group2 extends HasElementTestBean { } + @Route("preserved") + @PreserveOnRefresh + public static class PreservedGroup extends HasElementTestBean { + } + + @PreserveOnRefresh + public static class PreservedLayout extends HasElementTestBean + implements RouterLayout { + } + + @RouteScoped + @RouteScopeOwner(PreservedGroup.class) + public static class MemberOfPreservedGroup extends HasElementTestBean { + + boolean isDestroyed; + + @PreDestroy + private void onDestroy() { + isDestroyed = true; + } + } + + /** + * A layout without {@link PreserveOnRefresh}, shared by a preserved and a + * plain child. Flow reuses the same layout instance when navigating between + * the two, and preserves it on refresh together with the preserved child. + */ + public static class SharedLayout extends HasElementTestBean + implements RouterLayout { + } + + @RouteScoped + @RouteScopeOwner(SharedLayout.class) + public static class MemberOfSharedLayout extends HasElementTestBean { + + boolean isDestroyed; + + @PreDestroy + private void onDestroy() { + isDestroyed = true; + } + } + @Route("") public static class InitialRoute extends HasElementTestBean { @@ -120,9 +165,17 @@ private static class CustomEvent { @RouteScopeOwner(Group1.class) private Provider memberOfGroup1; + @Inject + @RouteScopeOwner(PreservedGroup.class) + private Provider memberOfPreservedGroup; + @Inject private Provider noOwnerBean; + @Inject + @RouteScopeOwner(SharedLayout.class) + private Provider memberOfSharedLayout; + @Inject private Event beforeNavigationTrigger; @@ -230,9 +283,66 @@ public void afterNavigation_group2NavigationAftergroup1_beansAreDestroyed() { @Test public void preserveOnRefresh_anotherUIHasSameWindowName_beanIsPreserved() { + UI ui = doSetUp("foo", null); + Mockito.when(event.getNavigationTarget()) + .thenReturn((Class) PreservedGroup.class); + beforeNavigationTrigger.fire(event); + + MemberOfPreservedGroup bean1 = memberOfPreservedGroup.get(); + bean1.setState(STATE); + + // set another UI instance with the same window name into the context + doSetUp("foo", ui.getSession()); + Mockito.when(event.getNavigationTarget()) + .thenReturn((Class) PreservedGroup.class); + beforeNavigationTrigger.fire(event); + + ComponentUtil.onComponentDetach(ui); + + Assertions.assertFalse(bean1.isDestroyed); + Assertions.assertSame(bean1, memberOfPreservedGroup.get()); + Assertions.assertEquals(STATE, memberOfPreservedGroup.get().getState()); + } + + @Test + public void noPreserveOnRefresh_anotherUIHasSameWindowName_beanIsNotShared() { + UI ui = doSetUp("foo", null); + Mockito.when(event.getNavigationTarget()) + .thenReturn((Class) Group1.class); + beforeNavigationTrigger.fire(event); + + MemberOfGroup1 bean1 = memberOfGroup1.get(); + bean1.setState(STATE); + + // set another UI instance with the same window name into the context, + // simulating e.g. a page refresh or a duplicated browser tab + doSetUp("foo", ui.getSession()); + Mockito.when(event.getNavigationTarget()) + .thenReturn((Class) Group1.class); + beforeNavigationTrigger.fire(event); + + MemberOfGroup1 bean2 = memberOfGroup1.get(); + Assertions.assertNotSame(bean1, bean2, + "Beans of a not preserved navigation chain must not be shared " + + "between UIs of the same browser window"); + Assertions.assertNotEquals(STATE, bean2.getState()); + + // the bean of the first UI is still bound to that UI only, and is + // destroyed together with it + Assertions.assertFalse(bean1.isDestroyed); + ComponentUtil.onComponentDetach(ui); + Assertions.assertTrue(bean1.isDestroyed); + Assertions.assertFalse(bean2.isDestroyed); + } + + @Test + public void preserveOnRefreshLayout_anotherUIHasSameWindowName_beanIsPreserved() { UI ui = doSetUp("foo", null); Mockito.when(event.getNavigationTarget()) .thenReturn((Class) Group1.class); + Mockito.when(event.getLayouts()).thenReturn( + Collections.> singletonList( + PreservedLayout.class)); beforeNavigationTrigger.fire(event); MemberOfGroup1 bean1 = memberOfGroup1.get(); @@ -242,11 +352,15 @@ public void preserveOnRefresh_anotherUIHasSameWindowName_beanIsPreserved() { doSetUp("foo", ui.getSession()); Mockito.when(event.getNavigationTarget()) .thenReturn((Class) Group1.class); + Mockito.when(event.getLayouts()).thenReturn( + Collections.> singletonList( + PreservedLayout.class)); beforeNavigationTrigger.fire(event); ComponentUtil.onComponentDetach(ui); Assertions.assertFalse(bean1.isDestroyed); + Assertions.assertSame(bean1, memberOfGroup1.get()); Assertions.assertEquals(STATE, memberOfGroup1.get().getState()); } @@ -304,6 +418,112 @@ public void getActiveContextualStorages_getAllStoragesForGivenUI() { Assertions.assertNotSame(storage, storages.get(0)); } + @Test + public void sharedLayout_navigateFromPreservedChildToPlainChild_layoutBeanIsKept() { + doSetUp("foo", null); + + navigateTo(PreservedGroup.class, SharedLayout.class); + MemberOfSharedLayout bean1 = memberOfSharedLayout.get(); + bean1.setState(STATE); + + // the layout instance is reused by Flow, so its beans must survive + navigateTo(Group1.class, SharedLayout.class); + + MemberOfSharedLayout bean2 = memberOfSharedLayout.get(); + Assertions.assertFalse(bean1.isDestroyed, + "The layout owned bean must not be destroyed while the layout " + + "stays in the navigation chain"); + Assertions.assertSame(bean1, bean2, + "The layout owned bean must stay the same instance while the " + + "layout is reused across navigations"); + Assertions.assertEquals(STATE, bean2.getState()); + } + + @Test + public void sharedLayout_navigateFromPlainChildToPreservedChild_layoutBeanIsKept() { + doSetUp("foo", null); + + navigateTo(Group1.class, SharedLayout.class); + MemberOfSharedLayout bean1 = memberOfSharedLayout.get(); + bean1.setState(STATE); + + navigateTo(PreservedGroup.class, SharedLayout.class); + + MemberOfSharedLayout bean2 = memberOfSharedLayout.get(); + Assertions.assertFalse(bean1.isDestroyed, + "The layout owned bean must not be destroyed while the layout " + + "stays in the navigation chain"); + Assertions.assertSame(bean1, bean2, + "The layout owned bean must stay the same instance when the " + + "navigation chain becomes preserved"); + Assertions.assertEquals(STATE, bean2.getState()); + } + + @Test + public void sharedLayout_navigateBackAndForth_layoutBeanIsKept() { + doSetUp("foo", null); + + navigateTo(PreservedGroup.class, SharedLayout.class); + MemberOfSharedLayout bean = memberOfSharedLayout.get(); + bean.setState(STATE); + + navigateTo(Group1.class, SharedLayout.class); + MemberOfSharedLayout beanOnPlainChild = memberOfSharedLayout.get(); + navigateTo(PreservedGroup.class, SharedLayout.class); + + Assertions.assertFalse(bean.isDestroyed); + Assertions.assertSame(bean, beanOnPlainChild, + "The layout owned bean must stay the same instance when the " + + "navigation chain is not preserved anymore"); + Assertions.assertSame(bean, memberOfSharedLayout.get(), + "The layout owned bean must stay the same instance when the " + + "navigation chain is preserved again"); + Assertions.assertEquals(STATE, memberOfSharedLayout.get().getState()); + } + + @Test + public void sharedLayout_beanReboundToUI_isDestroyedOnUIDetach() { + UI ui = doSetUp("foo", null); + + navigateTo(PreservedGroup.class, SharedLayout.class); + MemberOfSharedLayout bean = memberOfSharedLayout.get(); + + // the chain is not preserved anymore, so the bean is bound to this UI + navigateTo(Group1.class, SharedLayout.class); + Assertions.assertSame(bean, memberOfSharedLayout.get()); + + // set another UI instance with the same window name into the context, + // simulating e.g. a page refresh + doSetUp("foo", ui.getSession()); + ComponentUtil.onComponentDetach(ui); + + Assertions.assertTrue(bean.isDestroyed, + "The layout owned bean is not preserved anymore, so it must be " + + "destroyed together with its UI"); + } + + @Test + public void sharedLayout_anotherUIHoldsPreservedChain_beanIsNotStolen() { + UI ui = doSetUp("foo", null); + + navigateTo(PreservedGroup.class, SharedLayout.class); + MemberOfSharedLayout bean1 = memberOfSharedLayout.get(); + bean1.setState(STATE); + + // set another UI instance with the same window name into the context, + // both UIs being alive at the same time + doSetUp("foo", ui.getSession()); + navigateTo(Group1.class, SharedLayout.class); + + MemberOfSharedLayout bean2 = memberOfSharedLayout.get(); + Assertions.assertNotSame(bean1, bean2, + "The beans of a not preserved navigation chain must not be " + + "taken from a UI that may still hold the preserved " + + "chain"); + Assertions.assertNotEquals(STATE, bean2.getState()); + Assertions.assertFalse(bean1.isDestroyed); + } + @Test public void onBeforeEnter_conditionalBean_doesNotThrow() { Mockito.when(event.getNavigationTarget()) @@ -312,6 +532,15 @@ public void onBeforeEnter_conditionalBean_doesNotThrow() { customEventEventTrigger.fire(new CustomEvent()); } + private void navigateTo(Class navigationTarget, + Class layout) { + Mockito.when(event.getNavigationTarget()).thenReturn(navigationTarget); + Mockito.when(event.getLayouts()).thenReturn( + Collections.> singletonList( + layout)); + beforeNavigationTrigger.fire(event); + } + private UI doSetUp(String windowName, VaadinSession session) { changeEvent = Mockito.mock(LocationChangeEvent.class);