Skip to content

Commit

Permalink
Feat/research ssr (#3962)
Browse files Browse the repository at this point in the history
  • Loading branch information
mariojsnunes authored Nov 1, 2024
1 parent 92f3423 commit 4a84ce3
Show file tree
Hide file tree
Showing 29 changed files with 757 additions and 961 deletions.
6 changes: 4 additions & 2 deletions packages/components/src/FollowButton/FollowButton.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMemo } from 'react'
import { useNavigate } from '@remix-run/react'

import { Button } from '../Button/Button'
Expand All @@ -15,14 +16,15 @@ export interface IProps {
export const FollowButton = (props: IProps) => {
const { hasUserSubscribed, isLoggedIn, onFollowClick, sx } = props
const navigate = useNavigate()
const uuid = useMemo(() => (Math.random() * 16).toString(), [])

return (
<>
<Button
type="button"
data-testid={isLoggedIn ? 'follow-button' : 'follow-redirect'}
data-cy={isLoggedIn ? 'follow-button' : 'follow-redirect'}
data-tooltip-id="login-follow"
data-tooltip-id={uuid}
data-tooltip-content={isLoggedIn ? '' : 'Login to follow'}
icon="thunderbolt"
variant="outline"
Expand All @@ -36,7 +38,7 @@ export const FollowButton = (props: IProps) => {
>
{hasUserSubscribed ? 'Following' : 'Follow'}
</Button>
<Tooltip id="login-follow" />
<Tooltip id={uuid} />
</>
)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useMemo, useState } from 'react'
import { useNavigate } from '@remix-run/react'
import { Text, useThemeUI } from 'theme-ui'

Expand All @@ -18,6 +18,7 @@ export interface IProps {
export const UsefulStatsButton = (props: IProps) => {
const { theme } = useThemeUI() as any
const navigate = useNavigate()
const uuid = useMemo(() => (Math.random() * 16).toString(), [])

const [disabled, setDisabled] = useState<boolean>()

Expand All @@ -35,7 +36,7 @@ export const UsefulStatsButton = (props: IProps) => {
<>
<Button
type="button"
data-tooltip-id="login-vote"
data-tooltip-id={uuid}
data-tooltip-content={props.isLoggedIn ? '' : 'Login to add your vote'}
data-cy={props.isLoggedIn ? 'vote-useful' : 'vote-useful-redirect'}
onClick={() =>
Expand Down Expand Up @@ -73,7 +74,7 @@ export const UsefulStatsButton = (props: IProps) => {
{props.hasUserVotedUseful ? 'Marked as useful' : 'Mark as useful'}
</Text>
</Button>
<Tooltip id="login-vote" />
<Tooltip id={uuid} />
</>
)
}
5 changes: 3 additions & 2 deletions packages/cypress/src/integration/questions/write.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { MOCK_DATA } from '../../data'
import { generateAlphaNumeric } from '../../utils/TestUtils'

const questions = Object.values(MOCK_DATA.questions)
const item = questions[0]

describe('[Question]', () => {
describe('[Create a question]', () => {
const initialRandomId = crypto.randomUUID().slice(0, 8)
const initialRandomId = generateAlphaNumeric(8).toLowerCase()
const initialTitle = initialRandomId + ' Health cost of plastic?'
const initialExpectedSlug = initialRandomId + '-health-cost-of-plastic'
const initialQuestionDescription =
"Hello! I'm wondering how people feel about the health concerns about working with melting plastic and being in environments with microplastics. I have been working with recycling plastic (hdpe) for two years now, shredding and injection molding and haven't had any bad consequences yet. But with the low knowledge around micro plastics and its effects on the human body, and many concerns and hypotheses I have been a bit concerned lately.So I would like to ask the people in this community how you are feeling about it, and if you have experienced any issues with the microplastics or gases yet, if so how long have you been working with it? And what extra steps do you take to be protected from it? I use a gas mask with dust filters"
const category = 'exhibition'
const tag1 = 'product'
const tag2 = 'workshop'
const updatedRandomId = crypto.randomUUID().slice(0, 8)
const updatedRandomId = generateAlphaNumeric(8).toLowerCase()
const updatedTitle = updatedRandomId + ' Real health cost of plastic?'
const updatedExpectedSlug = updatedRandomId + '-real-health-cost-of-plastic'
const updatedQuestionDescription = `${initialQuestionDescription} and super awesome goggles`
Expand Down
5 changes: 3 additions & 2 deletions packages/cypress/src/integration/research/write.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { faker } from '@faker-js/faker'

import { RESEARCH_TITLE_MIN_LENGTH } from '../../../../../src/pages/Research/constants'
import {
generateAlphaNumeric,
generateNewUserDetails,
setIsPreciousPlastic,
} from '../../utils/TestUtils'
Expand Down Expand Up @@ -154,7 +155,7 @@ describe('[Research]', () => {
})

it('[Any PP user]', () => {
const randomId = crypto.randomUUID().slice(0, 8)
const randomId = generateAlphaNumeric(8).toLowerCase()
const title = randomId + ' PP plastic stuff'
const expectSlug = randomId + '-pp-plastic-stuff'
const description = 'Bespoke research topic'
Expand Down Expand Up @@ -255,7 +256,7 @@ describe('[Research]', () => {

describe('[Displays draft updates for Author]', () => {
it('[By Authenticated]', () => {
const randomId = crypto.randomUUID().slice(0, 8)
const randomId = generateAlphaNumeric(8).toLowerCase()
const updateTitle = `${randomId} Create a research update`
const updateDescription = 'This is the description for the update.'
const updateVideoUrl = 'http://youtube.com/watch?v=sbcWY7t-JX8'
Expand Down
37 changes: 4 additions & 33 deletions src/pages/Howto/Content/EditHowto/EditHowto.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import React, { useEffect, useState } from 'react'
import React, { useState } from 'react'
import { Navigate } from '@remix-run/react'
import { toJS } from 'mobx'
import { Loader } from 'oa-components'
import { useCommonStores } from 'src/common/hooks/useCommonStores'
import { isAllowedToEditContent } from 'src/utils/helpers'
import { Text } from 'theme-ui'
Expand All @@ -12,7 +10,6 @@ import type { IHowtoDB, IUser } from 'oa-shared'

interface IState {
formValues: IHowtoDB
isLoading: boolean
loggedInUser?: IUser | undefined
}

Expand All @@ -22,37 +19,11 @@ type EditHowtoProps = {

const EditHowto = ({ howto }: EditHowtoProps) => {
const { howtoStore } = useCommonStores().stores
const [{ formValues, isLoading, loggedInUser }, setState] = useState<IState>({
formValues: {} as IHowtoDB,
isLoading: true,
loggedInUser: undefined,
const [{ formValues, loggedInUser }] = useState<IState>({
formValues: howto,
loggedInUser: howtoStore.activeUser as IUser,
})

useEffect(() => {
const loggedInUser = howtoStore.activeUser
const init = async () => {
if (howto) {
setState({
formValues: toJS(howto) as IHowtoDB,
isLoading: false,
loggedInUser: loggedInUser ? loggedInUser : undefined,
})
} else {
setState({
formValues: howto,
isLoading: false,
loggedInUser: loggedInUser ? (loggedInUser as IUser) : undefined,
})
}
}

init()
}, [])

if (isLoading) {
return <Loader />
}

if (!formValues) {
return (
<Text mt="50px" sx={{ width: '100%', textAlign: 'center' }}>
Expand Down
11 changes: 2 additions & 9 deletions src/pages/Howto/Content/Howto/Howto.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export const Howto = observer(({ howto }: HowtoParams) => {
}, [howtoStore?.activeUser])

const onUsefulClick = async (
howToSlug: string,
vote: 'add' | 'delete',
eventCategory: string,
) => {
Expand All @@ -69,7 +68,7 @@ export const Howto = observer(({ howto }: HowtoParams) => {
trackEvent({
category: eventCategory,
action: vote === 'add' ? 'HowtoUseful' : 'HowtoUsefulRemoved',
label: howToSlug,
label: howto.slug,
})
}

Expand All @@ -79,17 +78,12 @@ export const Howto = observer(({ howto }: HowtoParams) => {
<HowtoDescription
howto={howto}
key={howto._id}
needsModeration={howtoStore.needsModeration(howto)}
loggedInUser={loggedInUser as IUser}
commentsCount={totalCommentsCount}
votedUsefulCount={usefulCount}
hasUserVotedUseful={voted}
onUsefulClick={async () =>
await onUsefulClick(
howto.slug,
voted ? 'delete' : 'add',
'HowtoDescription',
)
await onUsefulClick(voted ? 'delete' : 'add', 'HowtoDescription')
}
/>
<Box sx={{ mt: 9 }}>
Expand Down Expand Up @@ -139,7 +133,6 @@ export const Howto = observer(({ howto }: HowtoParams) => {
isLoggedIn={!!loggedInUser}
onUsefulClick={() =>
onUsefulClick(
howto.slug,
voted ? 'delete' : 'add',
'ArticleCallToAction',
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import type { IHowtoDB, ITag, IUser } from 'oa-shared'
interface IProps {
howto: IHowtoDB & { tagList?: ITag[] }
loggedInUser: IUser | undefined
needsModeration: boolean
commentsCount: number
votedUsefulCount?: number
verified?: boolean
Expand Down Expand Up @@ -110,17 +109,14 @@ const HowtoDescription = ({ howto, loggedInUser, ...props }: IProps) => {
<ClientOnly fallback={<></>}>
{() => (
<>
{props.votedUsefulCount !== undefined &&
howto.moderation === IModerationStatus.ACCEPTED && (
<Box>
<UsefulStatsButton
votedUsefulCount={props.votedUsefulCount}
hasUserVotedUseful={props.hasUserVotedUseful}
isLoggedIn={loggedInUser ? true : false}
onUsefulClick={props.onUsefulClick}
/>
</Box>
)}
{howto.moderation === IModerationStatus.ACCEPTED && (
<UsefulStatsButton
votedUsefulCount={props.votedUsefulCount}
hasUserVotedUseful={props.hasUserVotedUseful}
isLoggedIn={loggedInUser ? true : false}
onUsefulClick={props.onUsefulClick}
/>
)}
</>
)}
</ClientOnly>
Expand Down
29 changes: 20 additions & 9 deletions src/pages/Research/Content/Common/Research.form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as React from 'react'
import { useEffect, useState } from 'react'
import { Field, Form } from 'react-final-form'
import arrayMutators from 'final-form-arrays'
import { observer } from 'mobx-react'
Expand Down Expand Up @@ -41,13 +41,14 @@ import {
import { buttons, headings, overview } from '../../labels'
import ResearchFieldCategory from './ResearchCategorySelect'

import type { IResearch } from 'oa-shared'
import type { IResearch, IResearchDB } from 'oa-shared'
import type { MainFormAction } from 'src/common/Form/types'

interface IProps {
'data-testid'?: string
formValues: any
parentType: MainFormAction
research?: IResearchDB
}

const ResearchFormLabel = ({ children, ...props }) => (
Expand All @@ -72,22 +73,27 @@ const ResearchForm = observer((props: IProps) => {
} = overview

const store = useResearchStore()
const [showSubmitModal, setShowSubmitModal] = React.useState(false)
const [submissionHandler, setSubmissionHandler] = React.useState({
const [showSubmitModal, setShowSubmitModal] = useState(false)
const [submissionHandler, setSubmissionHandler] = useState({
draft: formValues.moderation === IModerationStatus.DRAFT,
shouldSubmit: false,
})
const [slug, setSlug] = useState<string>('')

// Managing locked state
React.useEffect(() => {
if (store.activeUser) store.lockResearchItem(store.activeUser.userName)
useEffect(() => {
if (store.activeUser && props.research) {
store.lockResearchItem(props.research, store.activeUser.userName)
}

return () => {
store.unlockResearchItem()
if (props.research) {
store.unlockResearchItem(props.research)
}
}
}, [store.activeUser])

React.useEffect(() => {
useEffect(() => {
if (submissionHandler.shouldSubmit) {
const form = document.getElementById('researchForm')
if (typeof form !== 'undefined' && form !== null) {
Expand All @@ -103,7 +109,11 @@ const ResearchForm = observer((props: IProps) => {
formValues.moderation = submissionHandler.draft
? IModerationStatus.DRAFT
: IModerationStatus.ACCEPTED // No moderation for researches for now
await store.uploadResearch(formValues)
const updatedResearh = await store.uploadResearch(formValues)

if (updatedResearh) {
setSlug(updatedResearh.slug)
}
}

const pageTitle = headings.overview[parentType]
Expand All @@ -112,6 +122,7 @@ const ResearchForm = observer((props: IProps) => {
<div data-testid={props['data-testid']}>
{showSubmitModal && (
<ResearchSubmitStatus
slug={slug}
onClose={() => {
setShowSubmitModal(false)
store.resetResearchUploadStatus()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { createMemoryRouter, RouterProvider } from 'react-router-dom'
import { createRoutesFromElements, Route } from '@remix-run/react'
import { render } from '@testing-library/react'
import { ThemeProvider } from '@theme-ui/core'
import { FactoryResearchItemUpdate } from 'src/test/factories/ResearchItem'
import {
FactoryResearchItem,
FactoryResearchItemUpdate,
} from 'src/test/factories/ResearchItem'
import { testingThemeStyles } from 'src/test/utils/themeUtils'
import { describe, expect, it, vi } from 'vitest'

Expand Down Expand Up @@ -43,7 +46,7 @@ vi.mock('src/stores/Research/research.store', () => {
Complete: false,
},
isTitleThatReusesSlug: vi.fn(),
unlockResearchUpdate: vi.fn(),
toggleLockResearchUpdate: vi.fn(),
}),
}
})
Expand Down Expand Up @@ -86,6 +89,7 @@ const getWrapper = (formValues, parentType, navProps) => {
index
element={
<ResearchUpdateForm
research={FactoryResearchItem()}
formValues={formValues}
parentType={parentType}
{...navProps}
Expand Down
Loading

0 comments on commit 4a84ce3

Please sign in to comment.