Skip to content

Commit

Permalink
clean up and use clsx more
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed Dec 30, 2023
1 parent 5daaf7e commit 0146e05
Show file tree
Hide file tree
Showing 14 changed files with 151 additions and 185 deletions.
59 changes: 18 additions & 41 deletions app/[...slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,29 @@ import {getPathsFromContext} from "@lib/drupal/get-paths";
import {getNodeMetadata} from "./metadata";
import {getPathFromContext, isDraftMode} from "@lib/drupal/utils";
import {PageProps} from "@lib/types";
import {graphqlClient} from "@lib/gql/fetcher";
import {NodeUnion, RouteQuery} from "@lib/gql/__generated__/drupal";
import {getAccessToken} from "@lib/drupal/get-access-token";
import {cache} from "@lib/drupal/get-cache";
import {getEntityFromPath} from "@lib/gql/fetcher";
import {NodeUnion} from "@lib/gql/__generated__/drupal";

// https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
export const revalidate = false;

const Page = async ({params}: PageProps) => {
const path = getPathFromContext({params})
const routeInfo = await getEntityFromPath<NodeUnion>(path)
if (routeInfo?.redirect?.url) redirect(routeInfo.redirect.url)
if (!routeInfo?.entity) notFound();

return (
<NodePage node={routeInfo.entity}/>
)
}

export const generateMetadata = async ({params}: PageProps): Promise<Metadata> => {
const path = getPathFromContext({params})

try {
const node = await getNodeForPath(path)
if (node) return getNodeMetadata(node);
const routeInfo = await getEntityFromPath<NodeUnion>(path, isDraftMode())
if (routeInfo?.entity) return getNodeMetadata(routeInfo.entity);
} catch (e) {
}
return {}
Expand Down Expand Up @@ -60,41 +69,9 @@ export const generateStaticParams = async () => {
page++;
}

return paths.map(path => typeof path !== "string" ? path?.params : path).slice(0, (completeBuild ? -1 : 1));
}

const Page = async ({params}: PageProps) => {
const path = getPathFromContext({params})
const node = await getNodeForPath(path)

if (!node) notFound();

return (
<NodePage node={node}/>
)
}

const getNodeForPath = async (path: string): Promise<NodeUnion | undefined> => {
const cacheKey = path.replaceAll('/', '--');
const token = await getAccessToken(isDraftMode());
let node = cache.get<NodeUnion>(cacheKey);

if (!node || token) {
let query: RouteQuery;
try {
query = await graphqlClient(token?.access_token).Route({path});
} catch (e) {
console.error(`Error fetching route data for '${path}'. ` + (e instanceof Error && e.message));
return;
}

if (query.route?.__typename === 'RouteRedirect') redirect(query.route.url);
node = query.route?.__typename === 'RouteInternal' ? query.route.entity as NodeUnion : undefined
}

// Just cache the node for 30 seconds so that any remaining queries during the build process will result in the cached data.
if (node) cache.set(cacheKey, node, 30);
return node;
return paths.filter(path => typeof path !== 'object' || path.params?.slug?.[0])
.map(path => typeof path === "object" ? path?.params : path)
.slice(0, (completeBuild ? -1 : 1))
}

export default Page;
30 changes: 8 additions & 22 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,43 +1,29 @@
import Rows from "@components/paragraphs/rows/rows";
import Paragraph from "@components/paragraphs/paragraph";
import {notFound} from "next/navigation";
import {graphqlClient} from "@lib/gql/fetcher";
import {getEntityFromPath} from "@lib/gql/fetcher";
import {NodeStanfordPage} from "@lib/gql/__generated__/drupal";
import {isDraftMode} from "@lib/drupal/utils";
import {getAccessToken} from "@lib/drupal/get-access-token";

// Cache the home page for 24 hours. It should be the most modified and probably changes more frequent.
// Cache the home page for 24 hours. It should be the most modified and probably changes most frequent.
export const revalidate = 86400;

const Home = async () => {
const node = await getHomePageNode();
if (!node) notFound();
const routeInfo = await getEntityFromPath<NodeStanfordPage>('/', isDraftMode());
if (!routeInfo?.entity) notFound();

return (
<article>
{node.suPageBanner &&
{routeInfo.entity.suPageBanner &&
<header aria-label="Home Page banner">
<Paragraph paragraph={node.suPageBanner}/>
<Paragraph paragraph={routeInfo.entity.suPageBanner}/>
</header>
}
{node.suPageComponents &&
<Rows components={node.suPageComponents}/>
{routeInfo.entity.suPageComponents &&
<Rows components={routeInfo.entity.suPageComponents}/>
}
</article>
)
}

const getHomePageNode = async (): Promise<NodeStanfordPage | undefined> => {
let node: NodeStanfordPage | false;
const token = await getAccessToken(isDraftMode());
try {
const query = await graphqlClient(token?.access_token).Route({path: '/'});
node = query.route?.__typename === 'RouteInternal' && query.route.entity as NodeStanfordPage
} catch (e) {
console.error('Error fetching home node. ' + (e instanceof Error && e.message));
return;
}
return node || undefined;
}

export default Home;
29 changes: 13 additions & 16 deletions src/components/elements/button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Link from "@components/elements/link";
import {twMerge} from 'tailwind-merge'
import {HtmlHTMLAttributes, MouseEventHandler} from "react";
import {Maybe} from "@lib/gql/__generated__/drupal";
import {clsx} from "clsx";


type Props = HtmlHTMLAttributes<HTMLAnchorElement | HTMLButtonElement> & {
Expand All @@ -10,30 +11,26 @@ type Props = HtmlHTMLAttributes<HTMLAnchorElement | HTMLButtonElement> & {
big?: boolean
secondary?: boolean
centered?: boolean
className?: Maybe<string>
onClick?: MouseEventHandler
prefetch?: boolean
}

export const Button = ({href, buttonElem = false, big = false, secondary = false, centered = false, children, className = "", ...props}: Props) => {
export const Button = ({href, buttonElem = false, big = false, secondary = false, centered = false, children, className, ...props}: Props) => {

className = twMerge(className, (centered ? "flex items-center w-fit mx-auto" : "inline-block text-center w-fit"))

if (big) {
// Big button styles.
className = twMerge(`btn btn--big transition text-5xl text-white hocus:text-white bg-digital-red hocus:bg-black no-underline hocus:underline py-6 px-12 font-normal`, className)
} else if (secondary) {
// Secondary button styles.
className = twMerge(`btn btn--secondary transition text-digital-red border-2 border-digital-red hocus:border-black no-underline hocus:underline py-4 px-8 font-normal`, className)
} else {
// Regular button styles.
className = twMerge(`btn bg-digital-red text-white hocus:bg-black hocus:text-white py-4 px-8 no-underline hocus:underline transition`, className)
}
const standardClasses = clsx(
{
'flex items-center w-fit mx-auto': centered,
'inline-block text-center w-fit': !centered,
'btn btn--big transition text-5xl text-white hocus:text-white bg-digital-red hocus:bg-black no-underline hocus:underline py-6 px-12 font-normal': big && !secondary,
'btn btn--secondary transition text-digital-red border-2 border-digital-red hocus:border-black no-underline hocus:underline py-4 px-8 font-normal': !big && secondary,
'btn bg-digital-red text-white hocus:bg-black hocus:text-white py-4 px-8 no-underline hocus:underline transition': !big && !secondary,
}
)

if (!href || buttonElem) {
return (
<button
className={className}
className={twMerge(standardClasses, className)}
type="button"
{...props}
>
Expand All @@ -45,7 +42,7 @@ export const Button = ({href, buttonElem = false, big = false, secondary = false
return (
<Link
href={href}
className={className}
className={twMerge(standardClasses, className)}
{...props}
>
{children}
Expand Down
20 changes: 8 additions & 12 deletions src/components/elements/headers.tsx
Original file line number Diff line number Diff line change
@@ -1,55 +1,51 @@
import {HtmlHTMLAttributes, ReactElement} from "react";
import {HtmlHTMLAttributes} from "react";
import {twMerge} from "tailwind-merge";
import {Maybe} from "@lib/gql/__generated__/drupal";

type Props = HtmlHTMLAttributes<HTMLHeadingElement> & {
className?: Maybe<string>
children: ReactElement | ReactElement[] | string
}
type Props = HtmlHTMLAttributes<HTMLHeadingElement>

const headingLinkClasses = "[&_a]:text-digital-red [&_a]:hocus:text-black [&_a]:hocus:underline";

export const H1 = ({children, className = '', ...props}: Props) => {
export const H1 = ({children, className, ...props}: Props) => {
return (
<h1 className={twMerge(className, "text-m4")} {...props}>
{children}
</h1>
)
}

export const H2 = ({children, className = '', ...props}: Props) => {
export const H2 = ({children, className, ...props}: Props) => {
return (
<h2 className={twMerge(headingLinkClasses, 'text-m3', className)} {...props}>
{children}
</h2>
)
}

export const H3 = ({children, className = '', ...props}: Props) => {
export const H3 = ({children, className, ...props}: Props) => {
return (
<h3 className={twMerge(headingLinkClasses, 'text-m2', className)} {...props}>
{children}
</h3>
)
}

export const H4 = ({children, className = '', ...props}: Props) => {
export const H4 = ({children, className, ...props}: Props) => {
return (
<h4 className={twMerge(headingLinkClasses, 'text-m1', className)} {...props}>
{children}
</h4>
)
}

export const H5 = ({children, className = '', ...props}: Props) => {
export const H5 = ({children, className, ...props}: Props) => {
return (
<h5 className={twMerge(headingLinkClasses, className)} {...props}>
{children}
</h5>
)
}

export const H6 = ({children, className = '', ...props}: Props) => {
export const H6 = ({children, className, ...props}: Props) => {
return (
<h6 className={twMerge(headingLinkClasses, className)} {...props}>
{children}
Expand Down
8 changes: 3 additions & 5 deletions src/components/elements/interception-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@ import {XMarkIcon} from "@heroicons/react/20/solid";
import {useLockedBody} from "usehooks-ts";

const InterceptionModal = ({children, ...props}: HtmlHTMLAttributes<HTMLDialogElement>) => {
const overlay = useRef<HTMLDialogElement | null>(null);
const wrapper = useRef<HTMLDivElement | null>(null);
const overlay = useRef<HTMLDialogElement>(null);
const wrapper = useRef<HTMLDivElement>(null);
const router = useRouter();
useLockedBody(true)

const onDismiss = useCallback(() => router.back(), [router]);

const onClick = useCallback((e: React.MouseEvent) => {
if (e.target === overlay.current || e.target === wrapper.current) {
if (onDismiss) onDismiss();
}
if (e.target === overlay.current || e.target === wrapper.current) onDismiss();
}, [onDismiss, overlay, wrapper]);

const onKeyDown = useCallback((e: KeyboardEvent) => {
Expand Down
2 changes: 0 additions & 2 deletions src/components/elements/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ import {EnvelopeIcon} from "@heroicons/react/24/outline";
import ActionLink from "@components/elements/action-link";
import Button from "@components/elements/button";
import {LinkProps} from "next/dist/client/link";
import {Maybe} from "@lib/gql/__generated__/drupal";

type Props = HtmlHTMLAttributes<HTMLAnchorElement | HTMLButtonElement> & LinkProps & {
href: string
children: ReactNode | ReactNode[]
className?: Maybe<string>
}

const DrupalLink = ({href, className, prefetch = true, children, ...props}: Props) => {
Expand Down
1 change: 0 additions & 1 deletion src/components/images/stanford-wordmark.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {HtmlHTMLAttributes} from "react";

type Props = HtmlHTMLAttributes<SVGSVGElement> & {
className?: string
height?: number
width?: number
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/layouts/interior-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ const InteriorPage = async ({children, currentPath, ...props}: Props) => {

return (
<div className="centered flex gap-20" {...props}>
<SideNav menuItems={tree} currentPath={currentPath}/>
<section className="flex-grow">
{children}
</section>
<SideNav menuItems={tree} currentPath={currentPath}/>
</div>
)
}
Expand Down
Loading

0 comments on commit 0146e05

Please sign in to comment.