Skip to content

Commit

Permalink
Fix all typescript errors (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed Nov 13, 2023
1 parent 6b73786 commit ff1cb6a
Show file tree
Hide file tree
Showing 95 changed files with 1,207 additions and 1,148 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/build_lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
name: Build & Lint
on: [push]
jobs:
build-lint:
lint:
name: Lint & TS Check
runs-on: ubuntu-latest
container:
image: node:18.10
image: node:18
env:
NODE_ENV: development
NEXT_PUBLIC_DRUPAL_BASE_URL: ${{ secrets.NEXT_PUBLIC_DRUPAL_BASE_URL }}
Expand Down
21 changes: 11 additions & 10 deletions .storybook/stories/menu/SideMenu.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,25 @@ export const SideNavComponent: Story = {
{
id: 4,
title: "Parent Item",
url: "#",
url: "/foo",
items: [
{id: 5, title: "First Item", url: "#"},
{id: 5, title: "First Item", url: "/foo/bar"},
{
id: 6,
title: "Second Item",
url: "#",
url: "/foo/baz",
items: [
{id: 8, title: "First Item", url: "#"},
{id: 9, title: "Second Item", url: "#"},
{id: 10, title: "Third Item", url: "#"},
{id: 8, title: "First Item", url: "/foo/baz/foo"},
{id: 9, title: "Second Item", url: "/foo/baz/bar"},
{id: 10, title: "Third Item", url: "/foo/baz/bin"},
]
},
{id: 7, title: "Third Item", url: "#"},
{id: 7, title: "Third Item", url: "/foo/bin"},
]
},
{id: 2, title: "Second Item", url: "#"},
{id: 3, title: "Third Item", url: "#"},
]
{id: 2, title: "Second Item", url: "/bar"},
{id: 3, title: "Third Item", url: "/baz"},
],
currentPath: "/foo/baz/bin",
},
};
6 changes: 3 additions & 3 deletions app/@modal/(.)gallery-image/[filename]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import InterceptionModal from "@components/elements/interception-modal";
import {DrupalJsonApiParams} from "drupal-jsonapi-params";
import {getResourceCollection} from "@lib/drupal/get-resource";
import {File, DrupalGalleryImageMediaType} from "@lib/types";
import {DrupalGalleryImageMediaType, DrupalImageFileType} from "@lib/types";
import {randomUUID} from "crypto";


const Page = async ({params: {filename}}: { params: { filename: string } }) => {
const captionId = randomUUID();
const fileParams = new DrupalJsonApiParams();
fileParams.addFilter('filename', filename);
const files = await getResourceCollection<File[]>('file--file', {params: fileParams.getQueryObject()});
const files = await getResourceCollection<DrupalImageFileType[]>('file--file', {params: fileParams.getQueryObject()});
if (!files || files.length === 0) return null;

const file: File = files[0];
const file = files[0];

const mediaParams = new DrupalJsonApiParams();
mediaParams.addFilter('su_gallery_image.id', file.id);
Expand Down
17 changes: 9 additions & 8 deletions app/[...slug]/metadata.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
import {DrupalNode, DrupalParagraph} from "next-drupal";
import {
BasicPageNodeType,
EventNodeType,
NewsNodeType,
PersonNodeType,
PolicyNodeType,
StanfordNode,
StanfordParagraph,
WysiwygParagraphType
} from "@lib/types";
import {decode} from 'html-entities';

export const getNodeMetadata = (node: DrupalNode) => {
export const getNodeMetadata = (node: StanfordNode) => {
const defaultData = {
title: node.title,
}
switch (node.type) {
case 'node--stanford_page':
return {
...getBasicPageMetaData(node as BasicPageNodeType),
...getBasicPageMetaData(node),
...defaultData
}

case 'node--stanford_news':
return {
...getNewsMetaData(node as NewsNodeType),
...getNewsMetaData(node),
...defaultData
}

case 'node--stanford_event':
return {
...getEventMetaData(node as EventNodeType),
...getEventMetaData(node),
...defaultData
}

case 'node--stanford_person':
return {
...getPersonMetaData(node as PersonNodeType),
...getPersonMetaData(node),
...defaultData
}

Expand Down Expand Up @@ -131,8 +132,8 @@ const getPolicyMetaData = (node: PolicyNodeType) => {
}
}

const getFirstText = (components: DrupalParagraph[] = []) => {
const firstWysiwyg: WysiwygParagraphType | undefined = components.find(component => component.type === 'paragraph--stanford_wysiwyg');
const getFirstText = (components: StanfordParagraph[] = []) => {
const firstWysiwyg = components.find(component => component.type === 'paragraph--stanford_wysiwyg') as WysiwygParagraphType | undefined;
if (firstWysiwyg) {
return getCleanDescription(firstWysiwyg.su_wysiwyg_text);
}
Expand Down
58 changes: 30 additions & 28 deletions app/[...slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import {getResourceFromContext} from "@lib/drupal/get-resource";
import {translatePathFromContext} from "@lib/drupal/translate-path";
import {DrupalNode} from "next-drupal";
import {notFound, redirect} from "next/navigation";
import NodePage from "@components/nodes/pages/node-page";
import {GetStaticPathsResult, GetStaticPropsContext, Metadata} from "next";
import {GetStaticPathsResult, Metadata} from "next";
import {DrupalJsonApiParams} from "drupal-jsonapi-params";
import {getPathsFromContext} from "@lib/drupal/get-paths";
import {getNodeMetadata} from "./metadata";
import {getAccessToken} from "@lib/drupal/get-access-token";
import {isDraftMode} from "@lib/drupal/utils";
import {PageProps, Params, StanfordNode} from "@lib/types";

export const revalidate = 86400;

export const generateMetadata = async (context: GetStaticPropsContext): Promise<Metadata> => {
let node: DrupalNode;
export const generateMetadata = async ({params}: PageProps): Promise<Metadata> => {
let node;
try {
node = await getPageData(context);
return getNodeMetadata(node);
node = await getPageData(params);
if (node) return getNodeMetadata(node);
} catch (e) {

}
Expand All @@ -29,41 +29,47 @@ class RedirectError extends Error {
}
}

const getPageData = async (context: GetStaticPropsContext) => {
const draftDev = isDraftMode()
const accessToken = draftDev ? await getAccessToken(true) : null;
const getPageData = async(params: Params): Promise<StanfordNode | undefined> => {
const draftMode = isDraftMode()
const accessToken = draftMode ? await getAccessToken(true) : null;

const path = await translatePathFromContext(context, accessToken ? {accessToken} : {});
const path = await translatePathFromContext({params}, accessToken ? {accessToken} : {});
// Check for redirect.
if (path?.redirect?.[0].to) {
const currentPath = '/' + (typeof context?.params?.slug === 'object' ? context.params.slug.join('/') : context?.params?.slug);
const [destination] = path.redirect;
if (path?.redirect && path?.redirect?.[0].to) {
const currentPath = '/' + (typeof params?.slug === 'object' ? params.slug.join('/') : params?.slug);

const [destination] = path.redirect;
if (destination.to != currentPath) {
throw new RedirectError(destination.to);
}

}

if (!path || !path.jsonapi) {
throw new Error('Unable to translate path')
}

if (context?.params?.slug?.[0] === 'node' && path?.entity?.path) {
if (params?.slug?.[0] === 'node' && path?.entity?.path) {
throw new RedirectError(path.entity.path);
}
return getResourceFromContext<DrupalNode>(path.jsonapi.resourceName, context, {}, draftDev)
return getResourceFromContext<StanfordNode>(path.jsonapi.resourceName, {params}, {draftMode})
}

export const generateStaticParams = async () => {
const params = new DrupalJsonApiParams();
params.addPageLimit(50);

let paths: GetStaticPathsResult["paths"] = await getPathsFromContext([
const contentTypes = [
'node--stanford_page',
'node--stanford_event',
'node--stanford_news',
'node--stanford_person'
], {}, {params: params.getQueryObject()});
'node--stanford_person',
'node--stanford_policy',
'node--stanford_publication',
'node--stanford_course',
]

let paths: GetStaticPathsResult["paths"] = await getPathsFromContext(contentTypes, {}, {params: params.getQueryObject()});

let fetchMore = process.env.BUILD_COMPLETE === 'true';
let fetchedData: GetStaticPathsResult["paths"] = []
Expand All @@ -72,29 +78,25 @@ export const generateStaticParams = async () => {
console.log('Fetching page ' + page);
params.addPageOffset(page * 50);

fetchedData = await getPathsFromContext([
'node--stanford_page',
'node--stanford_event',
'node--stanford_news',
'node--stanford_person'
], {}, {params: params.getQueryObject()})
fetchedData = await getPathsFromContext(contentTypes, {}, {params: params.getQueryObject()})
paths = [...paths, ...fetchedData];
fetchMore = fetchedData.length > 0;
page++;
}

return paths.map(path => typeof path !== "string" ? path?.params : path).slice(0, (process.env.BUILD_COMPLETE ? -1 : 1));
return paths.map(path => typeof path !== "string" ? path?.params : path).slice(0, (process.env.BUILD_COMPLETE === 'true' ? -1 : 1));
}

const Page = async (context: GetStaticPropsContext) => {
let node;
const Page = async ({params}: PageProps) => {
let node = null;
try {
node = await getPageData(context);
node = await getPageData(params);
} catch (e) {
if (e instanceof RedirectError) {
redirect(e.message);
}
}

if (!node) notFound();

return (
Expand Down
4 changes: 2 additions & 2 deletions app/api/draft/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import {draftMode} from 'next/headers'
import {redirect} from 'next/navigation'
import {getResourceByPath} from "@lib/drupal/get-resource";
import {DrupalNode} from "next-drupal";
import {StanfordNode} from "@lib/types";

export async function GET(request: Request) {
// Parse query string parameters
Expand All @@ -20,7 +20,7 @@ export async function GET(request: Request) {

// Fetch the headless CMS to check if the provided `slug` exists
// getPostBySlug would implement the required fetching logic to the headless CMS
const node: DrupalNode = await getResourceByPath(slug, {}, true)
const node = await getResourceByPath<StanfordNode>(slug, {draftMode: true})

// If the slug doesn't exist prevent draft mode from being enabled
if (!node) {
Expand Down
4 changes: 3 additions & 1 deletion app/error.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

const Error = ({error, reset}: { error: Error; reset: () => void }) => {
const ErrorPage = ({error, reset}: { error: Error; reset: () => void }) => {
console.error(error.message);
return (
<div className="centered my-50">
Expand All @@ -11,3 +11,5 @@ const Error = ({error, reset}: { error: Error; reset: () => void }) => {
</div>
)
}

export default ErrorPage
4 changes: 2 additions & 2 deletions app/gallery-image/[filename]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {DrupalJsonApiParams} from "drupal-jsonapi-params";
import {getResourceCollection} from "@lib/drupal/get-resource";
import {notFound} from "next/navigation";
import {DrupalGalleryImageMediaType, File} from "@lib/types";
import {DrupalGalleryImageMediaType, DrupalImageFileType} from "@lib/types";
import {H1} from "@components/elements/headers";

export const metadata = {
Expand All @@ -15,7 +15,7 @@ const Page = async ({params: {filename}}: { params: { filename: string } }) => {

const fileParams = new DrupalJsonApiParams();
fileParams.addFilter('filename', filename);
const files = await getResourceCollection<File[]>('file--file', {params: fileParams.getQueryObject()});
const files = await getResourceCollection<DrupalImageFileType[]>('file--file', {params: fileParams.getQueryObject()});
if (files.length === 0) {
notFound();
}
Expand Down
8 changes: 4 additions & 4 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ export const metadata = {

export const revalidate = 3600;

const RootLayout = ({children, modal}: { children: React.ReactNode, modal?: React.ReactNode }) => {
const draftDev = isDraftMode();
const RootLayout = ({children, modal}: { children: React.ReactNode, modal: React.ReactNode }) => {
const draftMode = isDraftMode();
return (
<html lang="en" className={`${sourceSansPro.className} font-sans`}>
{draftDev && <Editori11y/>}
{(!draftDev && process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID) &&
{draftMode && <Editori11y/>}
{(!draftMode && process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID) &&
<>
<Script async src="//siteimproveanalytics.com/js/siteanalyze_80352.js"/>
<GoogleAnalytics/>
Expand Down
6 changes: 4 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import Rows from "@components/paragraphs/rows/rows";
import {BasicPageNodeType} from "@lib/types";
import Paragraph from "@components/paragraphs/paragraph";
import {isDraftMode} from "@lib/drupal/utils";
import {notFound} from "next/navigation";

export const revalidate = 86400;

const Home = async () => {
const draftDev = isDraftMode()
const node = await getResourceByPath<BasicPageNodeType>('/', {}, draftDev);
const draftMode = isDraftMode()
const node = await getResourceByPath<BasicPageNodeType>('/', {draftMode});
if(!node) notFound();

return (
<>
Expand Down
4 changes: 2 additions & 2 deletions app/search/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {getSearchIndex} from "@lib/drupal/get-search-index";
import {DrupalNode} from "next-drupal";
import SearchResults from "./search-results";
import {getNodeMetadata} from "../[...slug]/metadata";
import {H1} from "@components/elements/headers";
import {StanfordNode} from "@lib/types";

export const metadata = {
title: "Search",
Expand All @@ -18,7 +18,7 @@ const Page = () => {
const search = async (searchString: string) => {
"use server";

const searchResults: DrupalNode[] = await getSearchIndex('full_site_content', {params: {'filter[fulltext]': searchString}});
const searchResults: StanfordNode[] = await getSearchIndex('full_site_content', {params: {'filter[fulltext]': searchString}});
return searchResults.map(node => ({
id: node.id,
type: node.type,
Expand Down
13 changes: 7 additions & 6 deletions app/search/search-results.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import {useEffect, useRef, useState} from "react";
import {FormEvent, useEffect, useRef, useState} from "react";
import Link from "@components/elements/link";
import {useSearchParams} from "next/navigation";
import {Metadata} from "next";
Expand All @@ -16,23 +16,24 @@ interface Result extends Metadata {
}

const SearchResults = ({search}: { search: (search: string) => Promise<Result[]> }) => {
const inputRef = useRef(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const params = useSearchParams();
const [results, setResults] = useState<Result[]>([])
const [searchString, setSearchString] = useState<string>(params.get('q') ?? '')
const [isLoading, setIsLoading] = useState(false);
const [isLoading, setIsLoading] = useState<boolean>(false);

useEffect(() => {
search(params.get('q') ?? '').then(nodes => setResults(nodes));
}, [])

const onSubmit = (e) => {
const onSubmit = (e: FormEvent) => {
e.preventDefault();
setIsLoading(true)

search(inputRef.current.value).then(results => {
const searchString = inputRef.current?.value || '';
search(searchString).then(results => {
setResults(results);
setSearchString(inputRef.current.value);
setSearchString(searchString);
setIsLoading(false)
});
}
Expand Down
Loading

1 comment on commit ff1cb6a

@vercel
Copy link

@vercel vercel bot commented on ff1cb6a Nov 13, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.