Skip to content

Commit

Permalink
chore(genomepage): fix remaining eslint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ktun95 committed Mar 8, 2024
1 parent 80eb1ca commit 7dcc967
Show file tree
Hide file tree
Showing 37 changed files with 154 additions and 145 deletions.
1 change: 1 addition & 0 deletions apps/genome-page/common/@types/dicty-components-login.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/* eslint-disable unicorn/filename-case */
declare module "dicty-components-login"
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/* eslint-disable unicorn/filename-case */
declare module "dicty-components-navbar"
19 changes: 11 additions & 8 deletions apps/genome-page/common/hooks/WikiDisplay.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// group of functions that maps the markdown content/error to the corresponding react component
import * as E from "fp-ts/Either"
import {
type Either,
isRight as EisRight,
isLeft as EisLeft,
} from "fp-ts/Either"
import { guard } from "fp-ts-std/Function"
import { WikiContainer } from "../../components/features/CommunityAnnotations/WikiContainer"
import { WikiLoader } from "../../components/features/CommunityAnnotations/WikiLoader"
Expand All @@ -10,32 +14,31 @@ interface WikiContentProperties {
}

// type for Either monad
export type WikiContentEither = E.Either<string, WikiContentProperties>
export type WikiContentEither = Either<string, WikiContentProperties>

// predicate function that checks is the fetching is under process
const isLoading = (ma: WikiContentEither) => E.isRight(ma) && ma.right.loading
const isLoading = (ma: WikiContentEither) => EisRight(ma) && ma.right.loading

// predicate function to indicate if the fetching is completed
const isNotLoading = (ma: WikiContentEither) =>
E.isRight(ma) && !ma.right.loading
EisRight(ma) && !ma.right.loading

// react component for loading state
const loaderDisplay = () => <WikiLoader />

// react component for error display
const errorDisplay = (ma: WikiContentEither) =>
E.isLeft(ma) && <WikiContainer />
const errorDisplay = (ma: WikiContentEither) => EisLeft(ma) && <WikiContainer />

// react component for display markdown content
const nameDisplay = (ma: WikiContentEither) =>
E.isRight(ma) && <WikiContainer markdown={ma.right.markdown as string} />
EisRight(ma) && <WikiContainer markdown={ma.right.markdown as string} />

// react component when something unexpected happened
const defaultDisplay = () => <h2>Not sure what happened</h2>

// this function maps three conditions, error,success or loading to a react component
export const toOutput = guard([
[isLoading, loaderDisplay],
[E.isLeft, errorDisplay],
[EisLeft, errorDisplay],
[isNotLoading, nameDisplay],
])(defaultDisplay)
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { isMutation, getGraphQLServer } from "./useCreateApolloClient"

describe("isMutation function", () => {
Expand Down
14 changes: 5 additions & 9 deletions apps/genome-page/common/hooks/useCreateApolloClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,15 @@ const GENE_CACHE_KEY = "gene-apollo-cache-persist"

const mutationList = new Set(["Logout"])

const isMutation = (value: string) => {
if (mutationList.has(value)) {
return true
}
return false
}
const isMutation = (value: string) => mutationList.has(value)

const getGraphQLServer = (
url: string,
deployEnvironment: string,
origin: string,
) => {
if (deployEnvironment === "staging" && origin === "https://dictycr.org") {
return process.env.NEXT_PUBLIC_ALT_GRAPHQL_SERVER
return process.env.NEXT_PUBLIC_ALT_GRAPHQL_SERVER as string
}
return url
}
Expand All @@ -46,6 +41,7 @@ const authLink = setContext((request, { headers }) => {
})

const createApolloLink = (server: string): ApolloLink =>
// eslint-disable-next-line unicorn/prefer-spread -- this .concat is not Array.concat
authLink.concat(
createHttpLink({
uri: `${server}/graphql`,
Expand All @@ -59,8 +55,8 @@ const useCreateApolloClient = () => {

React.useEffect(() => {
const server = getGraphQLServer(
process.env.NEXT_PUBLIC_GRAPHQL_SERVER,
process.env.NEXT_PUBLIC_DEPLOY_ENV,
process.env.NEXT_PUBLIC_GRAPHQL_SERVER as string,
process.env.NEXT_PUBLIC_DEPLOY_ENV as string,
window.location.origin,
)
setLink(createApolloLink(server))
Expand Down
20 changes: 11 additions & 9 deletions apps/genome-page/common/hooks/useGithubWiki.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import { intercalate } from "fp-ts/Semigroup"
import http from "isomorphic-git/http/web"
import FS from "@isomorphic-git/lightning-fs"

export interface DirFileProps {
export interface DirectoryFileProperties {
dir: string
file: string
url: string
browserFS: FS
}

// The main wrapper function or hook
export function cloneGithubWiki(properties: DirFileProps) {
export function cloneGithubWiki(properties: DirectoryFileProperties) {
const defaultCloneParameters = {
http,
fs: properties.browserFS,
Expand All @@ -26,24 +26,22 @@ export function cloneGithubWiki(properties: DirFileProps) {
const defaultSeparator = "/"

// function that converts the data to a monad that handle promise
const wrapper = (properties_: DirFileProps) => of(properties_)
const wrapper = (properties_: DirectoryFileProperties) => of(properties_)

// function that runs the clone api and returns a promise, handles both the
// success and error conditons.
const executeCloneRepo = ({ dir, url, file }: DirFileProps) =>
const executeCloneRepo = ({ dir, url, file }: DirectoryFileProperties) =>
tryCatch(async () => {
await clone({ dir, url, ...defaultCloneParameters })
return { dir, url, file } as DirFileProps
return { dir, url, file } as DirectoryFileProperties
}, toError)
// const errLogger = TE.fromIOK(Console.error)
// const infoLogger = TE.fromIOK(Console.info)

// function that extract the error message from the Error object
const errorMessageExtract = (error: Error) => error.message

// function that constructs the markdown file path inside the git repo
const addPath = ({ dir, file }: DirFileProps) => {
const addPath = ({ dir, file }: DirectoryFileProperties) => {
const pathDelimGroup = pipe(Semigroup, intercalate(defaultSeparator))
// eslint-disable-next-line unicorn/prefer-spread -- this .concat is not Array.concat
return pathDelimGroup.concat(dir, file)
}

Expand All @@ -56,6 +54,10 @@ export function cloneGithubWiki(properties: DirFileProps) {
return buffer.toString()
}, toError)

// function that extract the error message from the Error object
// eslint-disable-next-line unicorn/consistent-function-scoping -- It's nice to keep this function here because these functions are defined in the order they are used in the flow below.
const errorMessageExtract = (error: Error) => error.message

// construct a pipeline from all the functions
const payload = flow(
wrapper,
Expand Down
3 changes: 2 additions & 1 deletion apps/genome-page/common/hooks/useGoogleAnalytics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const useGoogleAnalytics = () => {
const setGoogleAnalytics = async () => {
try {
const module = await import("react-ga")
const trackingID = process.env.NEXT_PUBLIC_GA_TRACKING_ID
const trackingID = process.env.NEXT_PUBLIC_GA_TRACKING_ID as string
const basename = process.env.NEXT_PUBLIC_BASENAME
const page = basename + router.pathname
const ReactGA = module.default
Expand All @@ -27,6 +27,7 @@ const useGoogleAnalytics = () => {
}
})
} catch (error) {
// eslint-disable-next-line no-console
console.error("could not load react-ga module", JSON.stringify(error))
}
}
Expand Down
49 changes: 24 additions & 25 deletions apps/genome-page/common/utils/containerGenerator.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-template-curly-in-string */
import { AssociatedSequencePanel } from "components/features/Summary/Panels/AssociatedSequencePanel"
import { GeneralInfoPanel } from "components/features/Summary/Panels/GeneralInfoPanel"
import { GoaPanel } from "components/features/Summary/Panels/GoaPanel"
Expand Down Expand Up @@ -31,31 +32,12 @@ interface SummaryContainerTypes {
allPublications: ContainerProperties
}

/*
containerGenerator returns ChildContent[] if the sectionId, element of arrayOfSections, exists.
Props:
- arrayOfSections: string[], an array of section ID's from the gene graphql query. You can console.log(gene) to understand.
- gene: GeneQuery, the GraphQL query that was made
*/
const containerGenerator = (arrayOfSections: string[], gene: GeneQuery) =>
arrayOfSections.map((sectionId) => {
if (gene[sectionId as keyof GeneQuery]) {
return {
panelProps:
SummaryContainerContent[sectionId as keyof SummaryContainerTypes],
child: returnComponentByName(
SummaryContainerContent[sectionId as keyof SummaryContainerTypes].id,
gene,
),
}
}
}) as ChildContent[]

/* An object that contains the Props of PanelWrapper for the respective sectionId */
const SummaryContainerContent = {
generalInformation: {
id: "generalInformation",
title: "General Information",
// eslint-disable-next-line sonarjs/no-duplicate-string
route: "/gene/${geneId}/",
},
gene: {
Expand Down Expand Up @@ -107,22 +89,39 @@ const returnComponentByName = (id: string, gene: GeneQuery) => {
case "allPublications":
return <ReferencesPanel gene={gene} />
default:
return <></>
}
}

/*
containerGenerator returns ChildContent[] if the sectionId, element of arrayOfSections, exists.
Props:
- arrayOfSections: string[], an array of section ID's from the gene graphql query. You can console.log(gene) to understand.
- gene: GeneQuery, the GraphQL query that was made
*/
const containerGenerator = (arrayOfSections: string[], gene: GeneQuery) =>
arrayOfSections
.filter((sectionId) => sectionId in gene)
.map((sectionId) => ({
panelProps:
SummaryContainerContent[sectionId as keyof SummaryContainerTypes],
child: returnComponentByName(
SummaryContainerContent[sectionId as keyof SummaryContainerTypes].id,
gene,
),
})) as ChildContent[]

/*
createRouteFromString returns the correct string path which can be used in the route prop of Panel Wrapper
Props:
- link: string
*/
const createRouteFromString = (link: string, gene: GeneQuery) => {
if ("/gene/${geneId}/references") {
const numberPubs = gene.allPublications.num_pubs.toString()
link = link.replace("${gene.allPublications.num_pubs}", numberPubs)
}
const numberPubs = gene.allPublications.num_pubs.toString()
const geneName = gene.gene!.name!.toString()
link = link.replace("${geneId}", geneName)
return link
.replace("${geneId}", geneName)
.replace("${gene.allPublications.num_pubs}", numberPubs)
}

export { containerGenerator, createRouteFromString, returnComponentByName }
9 changes: 5 additions & 4 deletions apps/genome-page/common/utils/headerItems.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react"
import { HeaderLink } from "dicty-components-header-footer"
import Link from "next/link"
Expand All @@ -8,17 +9,17 @@ import { SvgIconProps } from "@material-ui/core/SvgIcon"
import LogoutIcon from "@mui/icons-material/Logout"
import LoginIcon from "@mui/icons-material/Login"

type LinkIconProperties = {
link: LinkProperties
}

type LinkProperties = {
isRouter?: boolean
text: string
icon: React.ReactElement<SvgIconProps>
url: string
}

type LinkIconProperties = {
link: LinkProperties
}

const LinkIcon = ({ link }: LinkIconProperties) => (
<div style={{ textAlign: "center" }}>
{link.icon}
Expand Down
3 changes: 2 additions & 1 deletion apps/genome-page/common/utils/icons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,5 @@ library.add(
faWrench,
)

export { library as default } from "@fortawesome/fontawesome-svg-core"
// eslint-disable-next-line unicorn/prefer-export-from, import/no-default-export
export default library
23 changes: 7 additions & 16 deletions apps/genome-page/common/utils/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,20 @@
* @param initialValue
* @returns String with elements separated by a comma
*/
const commaSeparate = (array: string[], initialValue?: string): string =>
array.reduce((previous, current, index, _) => {
if (index === 0) return current
return `${previous}, ${current}`
}, initialValue || "")

const commaSeparate = (array: string[]): string => array.join(", ")
/**
* Given an array of strings, return a single string with elements separated by a comma and an "&"
* Ex. ["Mike", "Fox", "Tito"] -> "Mike, Fox & Tito"
* @param array
* @param initialValue
* @returns String with elements separated by a comma, and the last element with an "&"
*/
const commaSeparateWithAnd = (
array: string[],
initialValue?: string,
): string => {
const length_ = array.length
return array.reduce((previous, current, index, _) => {
if (index === 0) return current
if (index === length_ - 1) return `${previous} & ${current}`
return `${previous}, ${current}`
}, initialValue || "")
const commaSeparateWithAnd = (array: string[]): string => {
if (array.length === 0) return ""
if (array.length === 1) return array[0]
const init = array.slice(0, -1)
const last = array.at(-1)
return `${commaSeparate(init)} & ${last}`
}

export { commaSeparate, commaSeparateWithAnd }
1 change: 1 addition & 0 deletions apps/genome-page/common/utils/withLinkGenerator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ describe("withLinkGenerator", () => {
})
it("returns local URL if given gene ID", () => {
expect(function_("Q54QB1", "UniprotKB", "DDB_G0272608")).toBe(
// eslint-disable-next-line sonarjs/no-duplicate-string
"/gene/DDB_G0272608",
)
})
Expand Down
4 changes: 2 additions & 2 deletions apps/genome-page/components/LegacyLinkSnackbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { makeStyles } from "@material-ui/core/styles"
import InfoIcon from "@material-ui/icons/Info"
import LaunchIcon from "@material-ui/icons/Launch"

const useStyles = makeStyles((theme) => ({
const useStyles = makeStyles({
root: {
backgroundColor: "#f5f5f5",
marginBottom: "20px",
Expand All @@ -29,7 +29,7 @@ const useStyles = makeStyles((theme) => ({
linkIcon: {
verticalAlign: "middle",
},
}))
})

type Properties = {
/** Gene used to link to legacy page */
Expand Down
2 changes: 1 addition & 1 deletion apps/genome-page/components/Loader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import { Loader } from "components/Loader"
describe("components/Loader", () => {
it("should render Loader", () => {
render(<Loader />)
expect(screen.getByRole("loader")).toBeInTheDocument()
expect(screen.getByTestId("skeleton-loader")).toBeInTheDocument()
})
})
6 changes: 1 addition & 5 deletions apps/genome-page/components/Loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@ import { Skeleton } from "@mui/material"
* Loader is the default loading skeleton component.
*/
const Loader = () => (
<Grid
container
justifyContent="center"
data-testid="skeleton-loader"
role="loader">
<Grid container justifyContent="center" data-testid="skeleton-loader">
<Grid item xs={12}>
{new Array(10).map((item, key) => (
<Skeleton key={key} animation="wave" />
Expand Down
4 changes: 2 additions & 2 deletions apps/genome-page/components/errors/ErrorBoundary.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react"
import { render, screen } from "@testing-library/react"
import { ErrorBoundary } from "./ErrorBoundary"

const ErrComponent = () => {
const ErrorComponent = () => {
React.useEffect(() => {
throw new Error("My error")
}, [])
Expand All @@ -15,7 +15,7 @@ describe("components/errors/ErrorBoundary", () => {
it("should render error component", () => {
render(
<ErrorBoundary>
<ErrComponent />
<ErrorComponent />
</ErrorBoundary>,
)

Expand Down
Loading

0 comments on commit 7dcc967

Please sign in to comment.