Skip to content

Commit

Permalink
feat: next -> main (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ehesp authored Sep 24, 2024
1 parent 5f3667b commit 51329cf
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 14 deletions.
2 changes: 1 addition & 1 deletion website/src/components/Link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ export function Link(props: LinkProps) {
);
}

return <InternalLink {...props} href={"/getting-started"} />;
return <InternalLink {...props} href={href} />;
}
20 changes: 13 additions & 7 deletions website/src/components/Scripts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export function Scripts() {
const scripts = usePageContext().bundle.config.scripts;

// We don't want to load the scripts in preview mode or in preview environments.
if (ctx.preview || getEnvironment() !== "production") {
if (ctx.preview) {
return null;
}

Expand All @@ -20,15 +20,21 @@ export function Scripts() {
/>
)}
{!!scripts?.googleAnalytics && (
<Script
async
dangerouslySetInnerHTML={{
__html: `
<>
<Script
async
src={`https://www.googletagmanager.com/gtag/js?id=${scripts.googleAnalytics}`}
/>
<Script
async
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments)}
gtag('js', new Date()); gtag('config', '${scripts.googleAnalytics}');
`,
}}
/>
}}
/>
</>
)}
{"domain" in ctx && !!ctx.domain && !!scripts?.plausible && (
<Script
Expand Down
2 changes: 1 addition & 1 deletion website/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ function GroupHeading(props: { title: string; icon?: string }) {

// A recursive sidebar navigation component, renders a list of links and groups.
function SidebarLinks(
props: { pages: Pages } & { open: boolean; depth: number },
props: { pages: Pages } & { open: boolean; depth: number }
) {
return (
<ul aria-expanded={props.open}>
Expand Down
21 changes: 17 additions & 4 deletions website/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,13 @@ export async function getRequestContext(
) {
const { owner, repository, ref, path } = opts;

const vanity = request.headers["x-docs-page-vanity-domain"] !== undefined;
// Checks if the incoming request is from the vanity domain proxy.
const isVanityDomainRequest =
request.headers["x-docs-page-vanity-domain"] !== undefined;

// Checks if the incoming request is from a custom domain.
const isCustomDomainRequest =
request.headers["x-docs-page-custom-domain"] !== undefined;

const bundle = await getBundle({
owner,
Expand All @@ -68,6 +74,8 @@ export async function getRequestContext(
const environment = getEnvironment();

// Check whether the repository has a domain assigned.
// We still do this here since we need to know if internal links
// should be prefixed with the domain if one is set.
const domain = domains
.find(([, repo]) => repo === `${owner}/${repository}`)
?.at(0);
Expand All @@ -85,7 +93,7 @@ export async function getRequestContext(
}

let url = "";
if (vanity) {
if (isVanityDomainRequest) {
url = `https://${owner}.docs.page/${repository}`;
if (ref) url += `~${ref}`;
url += redirectTo;
Expand Down Expand Up @@ -115,8 +123,13 @@ export async function getRequestContext(
owner,
repository,
ref: ref || null,
domain: domain && environment === "production" ? domain : null,
vanity,
domain:
isCustomDomainRequest && environment === "development"
? "localhost:8787"
: domain && environment === "production"
? domain
: null,
vanity: isVanityDomainRequest,
bundle,
preview: false,
} satisfies Context;
Expand Down
125 changes: 125 additions & 0 deletions website/src/pages/[[...path]].tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import type { GetServerSideProps, InferGetServerSidePropsType } from "next";
import type { BundleErrorResponse } from "~/api";
import { type Context, getRequestContext } from "~/context";
import type { SharedEnvironmentVariables } from "~/env";

import { Documentation } from "~/layouts/Documentation";
import { Error } from "~/layouts/Error";
import { Homepage } from "~/layouts/homepage";
import { Site } from "~/layouts/Site";
import { Redirect, bundleCodeToStatusCode } from "~/utils";

export const getServerSideProps = (async ({ params, req, res }) => {
const env = {
VERCEL: process.env.VERCEL || null,
VERCEL_ENV: process.env.VERCEL_ENV || null,
VERCEL_GIT_COMMIT_SHA: process.env.VERCEL_GIT_COMMIT_SHA || null,
} satisfies SharedEnvironmentVariables;

const param = params?.path ? params.path : [];
const chunks = Array.isArray(param) ? param : [param];

// If there are no chunks, render the homepage.
if (chunks.length === 0) {
return { props: { env, ctx: null } };
}

// Any paths with only one chunk are invalid, and should be handled
// by other page routes.
if (chunks.length === 1) {
return { notFound: true };
}

// Any paths with two chunks or more are a repository page.
let [owner, repository, ...path] = chunks;
let ref: string | undefined;

// Check if the repo includes a ref (invertase/foo~bar)
if (repository.includes("~")) {
[repository, ref] = repository.split("~");
}

let ctx: Context | null = null;

try {
ctx = await getRequestContext(req, {
owner,
repository,
ref,
path: path.join("/"),
});
} catch (error) {
// If error is a Redirect instance
if (error instanceof Redirect) {
return {
redirect: {
destination: error.url,
permanent: false,
},
};
}

// If error is a Response instance
if (error instanceof Response) {
// Parse the response body as JSON.
const body = (await error.json()) as BundleErrorResponse;

// Set the status code to the bundle error code.
res.statusCode = bundleCodeToStatusCode(body);

return {
props: {
error: body,
},
};
}

throw error;
}

// Cache the response for 1 second, and revalidate in the background.
res.setHeader(
"Cache-Control",
"public, s-maxage=1, stale-while-revalidate=59"
);

return { props: { env, ctx } };
}) satisfies GetServerSideProps<
| {
env: SharedEnvironmentVariables;
ctx: Context | null;
}
| {
error: BundleErrorResponse;
}
>;

export default function Route({
env,
ctx,
error,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
// If there is an error, render the error page.
if (error) {
return (
<Site>
<Error error={error} />
</Site>
);
}

if (!ctx) {
return <Homepage />;
}

return (
<>
<script
dangerouslySetInnerHTML={{
__html: `window.ENV = ${env ? JSON.stringify(env) : "{}"}`,
}}
/>
<Documentation ctx={ctx} />
</>
);
}
4 changes: 3 additions & 1 deletion website/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import cx from "classnames";
import { twMerge } from "tailwind-merge";
import type { BundleResponse } from "./api";
import type { Context } from "./context";
import { getEnvironment } from "./env";

export class Redirect extends Error {
url: string;
Expand Down Expand Up @@ -114,7 +115,8 @@ export function getHref(ctx: Context, path: string) {
}
// Ensure all links start with the custom domain if it's set.
else if (ctx.domain) {
href += `https://${ctx.domain}`;
const protocol = getEnvironment() === 'development' ? 'http' : 'https';
href += `${protocol}://${ctx.domain}`;
}
// Prefix the path with the owner and repository, e.g. `/invertase/docs.page`.
else {
Expand Down

0 comments on commit 51329cf

Please sign in to comment.