Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions packages/vue-router/src/viewStacks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,19 @@ export const createViewStacks = (router: Router) => {
* This is needed otherwise Vue Router
* will not consider this component mounted
* and will not run route guards that
* are written in the component.
* are written in the component. Skip pages
* remounted behind the current one by `router.go(2)`,
* since they can share the current page's route record.
*/
const instance = viewItem.vueComponentRef.value;
viewItem.matchedRoute.instances = {
default: instance,
};
const isCurrentView =
findViewItemByPath(router.currentRoute.value.path, viewItem.outletId) ===
viewItem;
if (isCurrentView) {
viewItem.matchedRoute.instances = {
default: instance,
};
}

/**
* Run any callbacks passed to `next()` inside a
Expand Down Expand Up @@ -236,7 +243,6 @@ export const createViewStacks = (router: Router) => {
viewItem.mount = false;
viewItem.ionPageElement = undefined;
viewItem.ionRoute = false;
viewItem.matchedRoute.instances = {};
}
};

Expand Down
30 changes: 29 additions & 1 deletion packages/vue/src/components/IonRouterOutlet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,16 @@ export const IonRouterOutlet = /*@__PURE__*/ defineComponent({
);
const enteringEl = enteringViewItem.ionPageElement;

/**
* Views of a parameterized route (e.g. /page/:id) share a
* route record, so point it at the entering view or its
* in-component guards won't run.
*/
const enteringInstance = enteringViewItem.vueComponentRef.value;
if (enteringInstance) {
enteringViewItem.matchedRoute.instances.default = enteringInstance;
}

/**
* All views that can be transitioned to must have
* an `<ion-page>` element for transitions and lifecycle
Expand Down Expand Up @@ -660,7 +670,25 @@ See https://ionicframework.com/docs/vue/navigation#ionpage for more information.
components &&
components.map((c: any) => {
let props = {
ref: c.vueComponentRef,
ref: (instance: any) => {
/**
* Clear the route record on unmount like RouterView
* does, otherwise it keeps the page's DOM alive. Only
* read the ref here since reading it while mounting
* re-renders the outlet.
*/
if (instance === null) {
const { instances } = c.matchedRoute;
const previousInstance = c.vueComponentRef.value;
if (
previousInstance &&
instances.default === previousInstance
) {
instances.default = null;
}
}
c.vueComponentRef.value = instance;
},
key: c.pathname,
registerIonPage: (ionPageEl: HTMLElement) =>
registerIonPage(c, ionPageEl),
Expand Down
188 changes: 188 additions & 0 deletions packages/vue/test/base/tests/unit/detached-pages.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import { enableAutoUnmount, mount } from '@vue/test-utils';
import { afterEach, describe, expect, it } from 'vitest';
import { setFlagsFromString } from 'v8';
import { runInNewContext } from 'vm';
import { createRouter, createWebHistory } from '@ionic/vue-router';
import { IonicVue, IonApp, IonRouterOutlet, IonPage } from '@ionic/vue';
import { waitForRouter } from './utils';

/**
* Exposes `gc()` so the tests can check that a page is
* released once it leaves the DOM.
*/
Comment on lines +9 to +12

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Turning on --expose-gc at runtime doesn't add gc to the current global, only to contexts created afterward, so the comment doesn't explain why gc comes from runInNewContext
  • Without that, runInNewContext('gc') looks like a roundabout globalThis.gc, and simplifying it breaks every GC assertion in the file
Suggested change
/**
* Exposes `gc()` so the tests can check that a page is
* released once it leaves the DOM.
*/
/**
* Exposes `gc()` so the tests can check that a page is
* released once it leaves the DOM. Setting the flag at
* runtime only adds `gc` to contexts created afterward,
* so read it from a new one.
*/

setFlagsFromString('--expose-gc');
const gc: () => void = runInNewContext('gc');

const collectGarbage = async () => {
for (let i = 0; i < 5; i++) {
gc();
await new Promise((r) => setTimeout(r, 0));
}
};

const App = {
components: { IonApp, IonRouterOutlet },
template: '<ion-app><ion-router-outlet /></ion-app>',
};

const Home = {
components: { IonPage },
template: '<ion-page>Home</ion-page>',
};

const Detail = {
components: { IonPage },
props: ['id'],
template: '<ion-page class="detail">Detail {{ id }}</ion-page>',
};

const createGuardedDetail = (leftPages: string[]) => ({
...Detail,
beforeRouteLeave(this: { id: string }) {
leftPages.push(this.id);
},
});

const Settings = {
components: { IonPage },
template: '<ion-page>Settings</ion-page>',
};

const createAppRouter = (detail = Detail) =>
createRouter({
history: createWebHistory(process.env.BASE_URL),
routes: [
{ path: '/', component: Home },
{ path: '/message/:id', component: detail, props: true },
{ path: '/settings', component: Settings },
],
});

const mountApp = async (router: ReturnType<typeof createAppRouter>) => {
router.push('/');
await router.isReady();
return mount(App, {
global: { plugins: [router, IonicVue] },
attachTo: document.body,
});
};

enableAutoUnmount(afterEach);

describe('Detached pages', () => {
it('should release a page after navigating back from it', async () => {
const router = createAppRouter();
await mountApp(router);

router.push('/message/1');
await waitForRouter();
const detailPage = new WeakRef(document.querySelector('.detail')!);

router.back();
await waitForRouter();
expect(document.querySelector('.detail')).toBeNull();

await collectGarbage();
expect(detailPage.deref()).toBeUndefined();
});

it('should release a page after it is replaced', async () => {
const router = createAppRouter();
await mountApp(router);

router.push('/message/1');
await waitForRouter();
const detailPage = new WeakRef(document.querySelector('.detail')!);

router.replace('/settings');
await waitForRouter();
expect(document.querySelector('.detail')).toBeNull();

await collectGarbage();
expect(detailPage.deref()).toBeUndefined();
});

it('should release a page after navigating back to a page of the same route', async () => {
const router = createAppRouter();
await mountApp(router);

router.push('/message/1');
await waitForRouter();
router.push('/message/2');
await waitForRouter();
const secondDetailPage = new WeakRef(document.querySelectorAll('.detail')[1]);

router.back();
await waitForRouter();
expect(document.querySelectorAll('.detail').length).toBe(1);

await collectGarbage();
expect(secondDetailPage.deref()).toBeUndefined();
});

it('should run the leave guard of the page navigated back to', async () => {
const leftPages: string[] = [];
const router = createAppRouter(createGuardedDetail(leftPages));
await mountApp(router);

router.push('/message/1');
await waitForRouter();
router.push('/message/2');
await waitForRouter();

router.back();
await waitForRouter();
expect(router.currentRoute.value.path).toBe('/message/1');

router.push('/settings');
await waitForRouter();

expect(leftPages).toEqual(['1']);
});

it('should run the leave guard of the page navigated back to with router.go()', async () => {
const leftPages: string[] = [];
const router = createAppRouter(createGuardedDetail(leftPages));
await mountApp(router);

router.push('/message/1');
await waitForRouter();
router.push('/message/2');
await waitForRouter();
router.push('/message/3');
await waitForRouter();

router.go(-2);
await waitForRouter();
expect(router.currentRoute.value.path).toBe('/message/1');

router.push('/settings');
await waitForRouter();

expect(leftPages).toEqual(['1']);
});

it('should run the leave guard of the page navigated forward to with router.go()', async () => {
const leftPages: string[] = [];
const router = createAppRouter(createGuardedDetail(leftPages));
await mountApp(router);

router.push('/message/1');
await waitForRouter();
router.push('/message/2');
await waitForRouter();
router.push('/message/3');
await waitForRouter();

router.go(-2);
await waitForRouter();
router.go(2);
await waitForRouter();
expect(router.currentRoute.value.path).toBe('/message/3');

router.push('/settings');
await waitForRouter();

expect(leftPages).toEqual(['3']);
});
});
Loading