Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PCC-1805 Ensure starter kits compile when strict and strictNullChecks are enabled #329

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { serverSmartComponentMap } from "../../../../components/smart-components

export const pantheonAPIOptions: PantheonAPIOptions = {
resolvePath: (article) => `/articles/${article.slug || article.id}`,
getSiteId: () => process.env.PCC_SITE_ID,
getSiteId: () => process.env.PCC_SITE_ID as string,
smartComponentMap: serverSmartComponentMap,
componentPreviewPath: (componentName) =>
`/component-preview/${componentName}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,30 @@ import queryString from "query-string";
import { pantheonAPIOptions } from "../../api/pantheoncloud/[...command]/api-options";
import { ClientsideArticleView } from "./clientside-articleview";

export const ArticleView = async ({ params, searchParams }) => {
const { article, grant } = await getServersideArticle(params, searchParams);
export interface ArticleViewProps {
params: { uri: string };
searchParams: {
publishingLevel: "PRODUCTION" | "REALTIME";
pccGrant: string | undefined;
};
}

export const ArticleView = async ({
params,
searchParams,
}: ArticleViewProps) => {
const { article, grant } = await getServersideArticle({
params,
searchParams,
});

return <ClientsideArticleView article={article} grant={grant} />;
return <ClientsideArticleView article={article} grant={grant || undefined} />;
};

export async function getServersideArticle(params, searchParams) {
export async function getServersideArticle({
params,
searchParams,
}: ArticleViewProps) {
const { uri } = params;
const { publishingLevel, pccGrant, ...query } = searchParams;

Expand All @@ -20,7 +37,8 @@ export async function getServersideArticle(params, searchParams) {

const article = await PCCConvenienceFunctions.getArticleBySlugOrId(
slugOrId,
publishingLevel?.toString().toUpperCase() || "PRODUCTION",
(publishingLevel?.toString().toUpperCase() as "PRODUCTION" | "REALTIME") ||
"PRODUCTION",
);

if (!article) {
Expand All @@ -29,7 +47,8 @@ export async function getServersideArticle(params, searchParams) {

if (
article.slug?.trim().length &&
article.slug.toLowerCase() !== slugOrId?.trim().toLowerCase()
article.slug.toLowerCase() !== slugOrId?.trim().toLowerCase() &&
pantheonAPIOptions.resolvePath != null
) {
// If the article was accessed by the id rather than the slug - then redirect to the canonical
// link (mostly for SEO purposes than anything else).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ updateConfig({
});

export const ClientsideArticleView = ({
grant,
article,
grant,
}: {
grant: string;
article: Article;
grant?: string | undefined;
}) => {
return (
<PantheonProvider
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import { Suspense } from "react";
import Layout from "../../../components/layout";
import { SkeletonArticleView } from "../../../components/skeleton-article-view";
import { getSeoMetadata } from "../../../lib/utils";
import { ArticleView, getServersideArticle } from "./article-view";
import {
ArticleView,
ArticleViewProps,
getServersideArticle,
} from "./article-view";

export default async function ArticlePage({ params, searchParams }) {
export default async function ArticlePage({
params,
searchParams,
}: ArticleViewProps) {
return (
<Layout>
<div className="prose mx-4 mt-16 text-black sm:mx-6 md:mx-auto">
Expand All @@ -16,8 +23,11 @@ export default async function ArticlePage({ params, searchParams }) {
);
}

export async function generateMetadata({ params, searchParams }) {
const { article } = await getServersideArticle(params, searchParams);
export async function generateMetadata({
params,
searchParams,
}: ArticleViewProps) {
const { article } = await getServersideArticle({ params, searchParams });

return getSeoMetadata(article);
}
4 changes: 2 additions & 2 deletions starters/nextjs-starter-approuter-ts/app/articles/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import ArticleList from "../../components/article-list";
import Layout from "../../components/layout";
import { PAGE_SIZE } from "../../constants";

async function fetchNextPages(cursor: string) {
async function fetchNextPages(cursor?: string | null | undefined) {
"use server";
const { data, cursor: newCursor } =
await PCCConvenienceFunctions.getPaginatedArticles({
pageSize: PAGE_SIZE,
cursor,
cursor: cursor || undefined,
});
return {
data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export async function generateStaticParams() {

return publishedArticles.flatMap((article) => {
const params = [{ uri: article.id }];
if (article.metadata.slug) {
if (article.metadata?.slug) {
params.push({ uri: String(article.metadata.slug) });
}
return params;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ export const metadata: Metadata = {
description: "Example of using SSG and ISR",
};

async function fetchNextPages(cursor: string) {
async function fetchNextPages(cursor?: string | null | undefined) {
"use server";
const { data, cursor: newCursor } =
await PCCConvenienceFunctions.getPaginatedArticles({
pageSize: PAGE_SIZE,
cursor,
cursor: cursor || undefined,
});

return {
Expand Down
3 changes: 2 additions & 1 deletion starters/nextjs-starter-approuter-ts/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { Poppins } from "next/font/google";
// import Script from "next/script";

import "../styles/globals.css";
import { PropsWithChildren } from "react";

const poppins = Poppins({
subsets: ["latin"],
weight: ["400", "500", "700"],
});

function MyApp({ children }) {
function MyApp({ children }: PropsWithChildren) {
return (
<html>
<head>
Expand Down
16 changes: 11 additions & 5 deletions starters/nextjs-starter-approuter-ts/app/search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ import { PCCConvenienceFunctions } from "@pantheon-systems/pcc-react-sdk/server"
import Layout from "../../components/layout";
import SearchResults from "./search-results";

export default async function SearchPage({ searchParams }) {
interface Props {
searchParams: { q?: string | null | undefined };
}

export default async function SearchPage({ searchParams }: Props) {
const searchResults = await PCCConvenienceFunctions.getAllArticlesWithSummary(
{
publishingLevel: "PRODUCTION",
},
{
bodyContains: searchParams.q,
},
searchParams.q
? {
bodyContains: searchParams.q,
}
: undefined,
true,
);

Expand All @@ -23,7 +29,7 @@ export default async function SearchPage({ searchParams }) {
);
}

export function generateMetadata({ searchParams }) {
export function generateMetadata({ searchParams }: Props) {
return {
title: `Search results for "${searchParams.q}"`,
description: `Search results for "${searchParams.q}"`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ export default function SearchResults({
<div className="w-full whitespace-pre-wrap break-words py-4">
{isLoading ? (
<Skeleton count={5} />
) : (
) : summary ? (
<Markdown>{summary}</Markdown>
)}
) : null}
</div>
</section>
) : null}

<div className="my-16 max-w-[707px]">
{isLoading || searchResults?.length > 0 ? (
{isLoading || (searchResults && searchResults.length > 0) ? (
(searchResults ?? Array.from({ length: 5 })).map((result, index) => (
<Fragment key={result?.id || index}>
<div>
Expand All @@ -59,11 +59,11 @@ export default function SearchResults({
<p className="my-2 line-clamp-4 whitespace-pre-wrap">
{isLoading ? (
<Skeleton count={4} />
) : (
) : result.snippet ? (
markdownToTxt(
result.snippet.replaceAll(/{#h\..*}\n/g, "\n"),
)
)}
) : null}
</p>
</div>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ interface Props {
articles: PaginatedArticle[] | ArticleWithoutContent[];
totalCount: number;
cursor: string;
fetcher: (cursor: string) => Promise<{
fetcher: (cursor?: string | null | undefined) => Promise<{
data: PaginatedArticle[] | ArticleWithoutContent[];
newCursor: string;
}>;
Expand Down
16 changes: 11 additions & 5 deletions starters/nextjs-starter-approuter-ts/components/grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export function ArticleGridCard({
isWide = false,
}: ArticleGridCardProps) {
const targetHref = `${basePath}/${article.metadata?.slug || article.id}`;
const imageSrc = article.metadata?.["Hero Image"] || null;
const imageSrc = (article.metadata?.["Hero Image"] as string) || null;

return (
<div
Expand Down Expand Up @@ -93,11 +93,11 @@ export function ArticleGridCard({
<h1 className="mb-3 text-xl font-semibold leading-7">
{article.title}
</h1>
{article.metadata?.["Description"] && (
{article.metadata?.["Description"] ? (
<p className="line-clamp-3 min-h-[4.5rem] text-gray-600">
{article.metadata?.["Description"]?.toString() || ""}
</p>
)}
) : null}
</div>
<Link href={targetHref} className="mt-8">
<Button size="large">View</Button>
Expand All @@ -107,12 +107,18 @@ export function ArticleGridCard({
);
}

function GridItemCoverImage({ imageSrc, imageAltText }) {
function GridItemCoverImage({
imageSrc,
imageAltText,
}: {
imageSrc: string | null;
imageAltText?: string | null | undefined;
}) {
return imageSrc != null ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={imageSrc}
alt={imageAltText}
alt={imageAltText || undefined}
className="h-full w-full object-cover"
/>
) : (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default function SearchBar() {
function SearchBarForm({
defaultSearchQuery,
}: {
defaultSearchQuery?: string;
defaultSearchQuery?: string | null | undefined;
}) {
const onSubmit: FormEventHandler<HTMLFormElement> = (e) => {
e.preventDefault();
Expand All @@ -96,7 +96,7 @@ function SearchBarForm({
>
<input
placeholder="Search"
defaultValue={defaultSearchQuery}
defaultValue={defaultSearchQuery || ""}
className="h-full w-full border-r border-inherit bg-transparent px-4 outline-none sm:min-w-[291px]"
required
name="search"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default function PageHeader({ title }) {
export default function PageHeader({ title }: { title: string }) {
return (
<header className="mb-8">
<h1 className="text-5xl font-bold">{title}</h1>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useEffect, useState } from "react";
interface Props {
cursor?: string;
initialArticles?: PaginatedArticle[] | ArticleWithoutContent[];
fetcher: (cursor: string) => Promise<{
fetcher: (cursor: string | null | undefined) => Promise<{
data: PaginatedArticle[] | ArticleWithoutContent[];
newCursor: string;
}>;
Expand Down
14 changes: 12 additions & 2 deletions starters/nextjs-starter-approuter-ts/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@ export function formatDate(input: string | number): string {
});
}

export function getSeoMetadata(article: ArticleWithoutContent): Metadata {
export function getSeoMetadata(
article: ArticleWithoutContent | null,
): Metadata {
if (article == null) {
return {
openGraph: {
type: "website",
},
};
}

const tags: string[] =
article.tags && article.tags.length > 0 ? article.tags : [];
const imageProperties = [
Expand Down Expand Up @@ -53,7 +63,7 @@ export function getSeoMetadata(article: ArticleWithoutContent): Metadata {
authors,
openGraph: {
type: "website",
title: article.title,
title: article.title || undefined,
images: imageProperties,
description,
},
Expand Down
2 changes: 1 addition & 1 deletion starters/nextjs-starter-approuter-ts/next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
3 changes: 2 additions & 1 deletion starters/nextjs-starter-approuter-ts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"strict": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
Expand Down
Loading
Loading