Skip to content

Commit

Permalink
Fallback redirect to root when switching variants (#2376)
Browse files Browse the repository at this point in the history
  • Loading branch information
spastorelli authored Jul 16, 2024
1 parent b8c136e commit aa8bbad
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 11 deletions.
6 changes: 3 additions & 3 deletions e2e/pages.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ const testCases: TestsCase[] = [

// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/v/2.0/reference/api-reference/pets',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/v/2.0/reference/api-reference/pets?fallback=true',
);
},
},
Expand All @@ -152,7 +152,7 @@ const testCases: TestsCase[] = [

// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/v/2.0/reference/api-reference/pets',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/v/2.0/reference/api-reference/pets?fallback=true',
);
},
},
Expand Down Expand Up @@ -187,7 +187,7 @@ const testCases: TestsCase[] = [

// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/v/2.0/reference/api-reference/pets',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/v/2.0/reference/api-reference/pets?fallback=true',
);
},
},
Expand Down
27 changes: 27 additions & 0 deletions src/app/(space)/(content)/[[...pathname]]/PageClientLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
'use client';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React from 'react';

import { useScrollToHash } from '@/components/hooks';

/**
Expand All @@ -9,5 +12,29 @@ export function PageClientLayout(props: {}) {
// We use this hook in the page layout to ensure the elements for the blocks
// are rendered before we scroll to the hash.
useScrollToHash();

useStripFallbackQueryParam();
return null;
}

/**
* Strip the fallback query parameter from current URL.
*
* When the user switches variants using the space dropdown, we pass a fallback=true parameter.
* This parameter indicates that we should redirect to the root page if the path from the
* previous variant doesn't exist in the new variant. If the path does exist, no redirect occurs,
* so we need to remove the fallback parameter.
*/
function useStripFallbackQueryParam() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

React.useEffect(() => {
if (searchParams.has('fallback')) {
const params = new URLSearchParams(searchParams.toString());
params.delete('fallback');
router.push(`${pathname}?${params.toString()}${window.location.hash ?? ''}`);
}
}, [router, pathname, searchParams]);
}
64 changes: 56 additions & 8 deletions src/app/(space)/(content)/[[...pathname]]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import React from 'react';
import { PageAside } from '@/components/PageAside';
import { PageBody, PageCover } from '@/components/PageBody';
import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
import { getContentTitle } from '@/lib/utils';
Expand All @@ -19,10 +19,12 @@ export const runtime = 'edge';
/**
* Fetch and render a page.
*/
export default async function Page(props: { params: PagePathParams }) {
const { params } = props;
export default async function Page(props: {
params: PagePathParams;
searchParams: { fallback?: string };
}) {
const { params, searchParams } = props;

const rawPathname = getPathnameParam(params);
const {
content: contentPointer,
contentTarget,
Expand All @@ -32,9 +34,14 @@ export default async function Page(props: { params: PagePathParams }) {
pages,
page,
document,
} = await fetchPageData(params);
const linksContext: PageHrefContext = {};
} = await getPageDataWithFallback({
pagePathParams: params,
searchParams,
redirectOnFallback: true,
});

const linksContext: PageHrefContext = {};
const rawPathname = getPathnameParam(params);
if (!page) {
const pathname = normalizePathname(rawPathname);
if (pathname !== rawPathname) {
Expand Down Expand Up @@ -114,8 +121,18 @@ export async function generateViewport({ params }: { params: PagePathParams }):
};
}

export async function generateMetadata({ params }: { params: PagePathParams }): Promise<Metadata> {
const { space, pages, page, customization, parent } = await fetchPageData(params);
export async function generateMetadata({
params,
searchParams,
}: {
params: PagePathParams;
searchParams: { fallback?: string };
}): Promise<Metadata> {
const { space, pages, page, customization, parent } = await getPageDataWithFallback({
pagePathParams: params,
searchParams,
});

if (!page) {
notFound();
}
Expand All @@ -136,3 +153,34 @@ export async function generateMetadata({ params }: { params: PagePathParams }):
},
};
}

/**
* Fetches the page data matching the requested pathname and fallback to root page when page is not found.
*/
async function getPageDataWithFallback(args: {
pagePathParams: PagePathParams;
searchParams: { fallback?: string };
redirectOnFallback?: boolean;
}) {
const { pagePathParams, searchParams, redirectOnFallback = false } = args;

const { pages, page: targetPage, ...otherPageData } = await fetchPageData(pagePathParams);

let page = targetPage;
const canFallback = !!searchParams.fallback;
if (!page && canFallback) {
const rootPage = resolveFirstDocument(pages, []);

if (redirectOnFallback && rootPage?.page) {
redirect(pageHref(pages, rootPage?.page));
}

page = rootPage?.page;
}

return {
...otherPageData,
pages,
page,
};
}
1 change: 1 addition & 0 deletions src/components/Header/SpacesDropdownMenuItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ function useVariantSpaceHref(variantSpaceUrl: string) {
const targetUrl = new URL(variantSpaceUrl);
targetUrl.pathname += `/${currentPathname}`;
targetUrl.pathname = targetUrl.pathname.replace(/\/{2,}/g, '/').replace(/\/$/, '');
targetUrl.searchParams.set('fallback', 'true');

return targetUrl.toString();
}
Expand Down

0 comments on commit aa8bbad

Please sign in to comment.