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

Feat/research ssr #3962

Merged
merged 10 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
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 const FollowButton = (props: IProps) => {
const { hasUserSubscribed, isLoggedIn, onFollowClick, sx } = props
const navigate = useNavigate()
const uuid = useMemo(() => (Math.random() * 16).toString(), [])
Dismissed Show dismissed Hide dismissed

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}
mariojsnunes marked this conversation as resolved.
Show resolved Hide resolved
data-tooltip-content={isLoggedIn ? '' : 'Login to follow'}
icon="thunderbolt"
variant="outline"
Expand All @@ -36,7 +38,7 @@
>
{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 const UsefulStatsButton = (props: IProps) => {
const { theme } = useThemeUI() as any
const navigate = useNavigate()
const uuid = useMemo(() => (Math.random() * 16).toString(), [])
Dismissed Show dismissed Hide dismissed

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

Expand All @@ -35,7 +36,7 @@
<>
<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 @@
{props.hasUserVotedUseful ? 'Marked as useful' : 'Mark as useful'}
</Text>
</Button>
<Tooltip id="login-vote" />
<Tooltip id={uuid} />
</>
)
}
4 changes: 2 additions & 2 deletions packages/cypress/src/integration/questions/write.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ const item = questions[0]

describe('[Question]', () => {
describe('[Create a question]', () => {
const initialRandomId = crypto.randomUUID().slice(0, 8)
const initialRandomId = (Math.random() * 16).toString()
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 = (Math.random() * 16).toString()
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
4 changes: 2 additions & 2 deletions packages/cypress/src/integration/research/write.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ describe('[Research]', () => {
})

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

describe('[Displays draft updates for Author]', () => {
it('[By Authenticated]', () => {
const randomId = crypto.randomUUID().slice(0, 8)
const randomId = (Math.random() * 16).toString()
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
Loading