5 Commits

105 changed files with 3856 additions and 8428 deletions

View File

@ -1,7 +0,0 @@
.next
.lighthouseci
coverage
node_modules
next-env.d.ts
**/workbox-*.js
**/sw.js

View File

@ -6,8 +6,7 @@
},
"env": {
"node": true,
"browser": true,
"jest": true
"browser": true
},
"rules": {
"prettier/prettier": "error",

View File

@ -41,6 +41,9 @@ jobs:
- name: 'Build'
run: 'npm run build'
- name: 'html-w3c-validator'
run: 'npm run test:html-w3c-validator'
- name: 'Lighthouse'
run: 'npm run test:lighthouse'
env:

View File

@ -0,0 +1,9 @@
{
"urls": [
"http://localhost:3000/",
"http://localhost:3000/authentication/forgot-password",
"http://localhost:3000/authentication/reset-password",
"http://localhost:3000/authentication/signin",
"http://localhost:3000/authentication/signup"
]
}

View File

@ -1,10 +1,6 @@
{
"*": ["editorconfig-checker"],
"*.{js,jsx,ts,tsx}": [
"prettier --write",
"eslint --fix",
"jest --findRelatedTests"
],
"*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix"],
"*.{css,scss,sass,json,jsonc,yml,yaml}": ["prettier --write"],
"*.md": ["prettier --write", "markdownlint --dot --fix"]
"*.{md,mdx}": ["prettier --write", "markdownlint-cli2 --fix"]
}

11
.markdownlint-cli2.jsonc Normal file
View File

@ -0,0 +1,11 @@
{
"config": {
"default": true,
"MD013": false,
"MD024": false,
"MD033": false,
"MD041": false
},
"globs": ["**/*.{md,mdx}"],
"ignores": ["**/node_modules"]
}

View File

@ -1,6 +0,0 @@
{
"default": true,
"MD013": false,
"MD033": false,
"MD041": false
}

View File

@ -1,15 +1,15 @@
FROM node:16.15.0 AS dependencies
FROM node:16.17.0 AS dependencies
WORKDIR /usr/src/app
COPY ./package*.json ./
RUN npm install
FROM node:16.15.0 AS builder
FROM node:16.17.0 AS builder
WORKDIR /usr/src/app
COPY ./ ./
COPY --from=dependencies /usr/src/app/node_modules ./node_modules
RUN npm run build
FROM node:16.15.0 AS runner
FROM node:16.17.0 AS runner
WORKDIR /usr/src/app
ENV NODE_ENV=production
COPY --from=builder /usr/src/app/next.config.js ./next.config.js

View File

@ -3,10 +3,10 @@ import Link from 'next/link'
import { useRouter } from 'next/router'
import { CogIcon } from '@heroicons/react/solid'
import { GuildsChannelsPath } from '../../Application'
import { Channel as ChannelType } from '../../../../models/Channel'
import { useGuildMember } from '../../../../contexts/GuildMember'
import { IconButton } from '../../../design/IconButton'
import { GuildsChannelsPath } from '../Application'
import { Channel as ChannelType } from '../../../models/Channel'
import { useGuildMember } from '../../../contexts/GuildMember'
import { IconButton } from '../../design/IconButton'
export interface ChannelProps {
path: GuildsChannelsPath

View File

@ -1 +0,0 @@
export * from './Channel'

View File

@ -1,7 +1,7 @@
import Image from 'next/image'
import { GuildWithDefaultChannelId } from '../../../../models/Guild'
import { IconLink } from '../../../design/IconLink'
import { GuildWithDefaultChannelId } from '../../../models/Guild'
import { IconLink } from '../../design/IconLink'
export interface GuildProps {
guild: GuildWithDefaultChannelId

View File

@ -1,18 +0,0 @@
import { render } from '@testing-library/react'
import { Guild } from './Guild'
import { guildExample } from '../../../../cypress/fixtures/guilds/guild'
describe('<Guild />', () => {
it('should render successfully', () => {
const { baseElement } = render(
<Guild
guild={{
...guildExample,
defaultChannelId: 1
}}
/>
)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1 +0,0 @@
export * from './Guild'

View File

@ -5,13 +5,13 @@ import useTranslation from 'next-translate/useTranslation'
import classNames from 'classnames'
import axios from 'axios'
import { Emoji } from '../../../Emoji'
import { ConfirmPopup } from '../../ConfirmPopup'
import { Emoji } from '../../Emoji'
import { ConfirmPopup } from '../ConfirmPopup'
import {
GuildPublic as GuildPublicType,
GuildWithDefaultChannelId
} from '../../../../models/Guild'
import { useAuthentication } from '../../../../tools/authentication'
} from '../../../models/Guild'
import { useAuthentication } from '../../../tools/authentication'
export interface GuildPublicProps {
guild: GuildPublicType

View File

@ -1 +0,0 @@
export * from './GuildPublic'

View File

@ -22,12 +22,15 @@ export const JoinGuildsPublic: React.FC = () => {
})
useEffect(() => {
authentication.socket.on('guilds', (data: SocketData<GuildPublicType>) => {
handleSocketData({ data, setItems })
})
authentication?.socket?.on(
'guilds',
(data: SocketData<GuildPublicType>) => {
handleSocketData({ data, setItems })
}
)
return () => {
authentication.socket.off('guilds')
authentication?.socket?.off('guilds')
}
}, [authentication.socket, setItems])

View File

@ -1,8 +1,8 @@
import Image from 'next/image'
import Link from 'next/link'
import { MemberWithPublicUser } from '../../../../models/Member'
import { Emoji } from '../../../Emoji'
import { MemberWithPublicUser } from '../../../models/Member'
import { Emoji } from '../../Emoji'
export interface MemberProps {
member: MemberWithPublicUser

View File

@ -1 +0,0 @@
export * from './Member'

View File

@ -41,6 +41,14 @@ export const MessageText: React.FC<MessageContentProps> = (props) => {
rehypePlugins={[[emojiPlugin], [rehypeKatex]]}
linkTarget='_blank'
components={{
a: (props) => {
return (
<a
className='text-green-800 hover:underline dark:text-green-400'
{...props}
/>
)
},
emoji: (props) => {
return <Emoji value={props.value} size={20} />
},

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { PopupGuild } from './PopupGuild'
describe('<PopupGuild />', () => {
it('should render successfully', () => {
const { baseElement } = render(<PopupGuild />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -3,7 +3,8 @@ import { PlusSmIcon, ArrowDownIcon } from '@heroicons/react/solid'
import classNames from 'classnames'
import Image from 'next/image'
import { PopupGuildCard } from './PopupGuildCard/PopupGuildCard'
import { PopupGuildCard } from './PopupGuildCard'
export interface PopupGuildProps {
className?: string
}

View File

@ -1,30 +0,0 @@
import { render } from '@testing-library/react'
import { PlusSmIcon } from '@heroicons/react/solid'
import Image from 'next/image'
import { PopupGuildCard } from './PopupGuildCard'
describe('<PopupGuildCard />', () => {
it('should render successfully', () => {
const { baseElement } = render(
<PopupGuildCard
image={
<Image
quality={100}
src='/images/svg/design/create-server.svg'
alt=''
width={230}
height={230}
/>
}
description='Create your own guild and manage everything within a few clicks !'
link={{
icon: <PlusSmIcon className='mr-2 h-8 w-8' />,
text: 'Create a server',
href: '/application/guilds/create'
}}
/>
)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1 +0,0 @@
export * from './PopupGuildCard'

View File

@ -1,12 +0,0 @@
import { render } from '@testing-library/react'
import { Sidebar } from './Sidebar'
describe('<Sidebar />', () => {
it('should render successfully', () => {
const { baseElement } = render(
<Sidebar direction='left' visible={true} isMobile={false} />
)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1,23 +0,0 @@
import { render } from '@testing-library/react'
import {
guildExample,
guildExample2
} from '../../../cypress/fixtures/guilds/guild'
import {
userExample,
userSettingsExample
} from '../../../cypress/fixtures/users/user'
import { UserProfile } from './UserProfile'
describe('<UserProfile />', () => {
it('should render successfully', () => {
const { baseElement } = render(
<UserProfile
user={{ ...userExample, settings: userSettingsExample }}
guilds={[guildExample, guildExample2]}
/>
)
expect(baseElement).toBeTruthy()
})
})

View File

@ -72,7 +72,7 @@ export const Authentication: React.FC<AuthenticationProps> = (props) => {
} else {
try {
const { data } = await api.post<Tokens>('/users/signin', formData)
const authentication = new AuthenticationClass(data)
const authentication = new AuthenticationClass(data, true)
authentication.signin()
await router.push('/application')
return null

View File

@ -24,7 +24,7 @@ export const AuthenticationSocialMedia: React.FC = () => {
useEffect(() => {
const data = router.query
if (isTokens(data)) {
const authentication = new Authentication(data)
const authentication = new Authentication(data, true)
authentication.signin()
router.push('/application').catch(() => {})
}

View File

@ -1,18 +0,0 @@
import { isStringWithOnlyOneEmoji } from './isStringWithOnlyOneEmoji'
describe('components/Emoji/isStringWithOnlyOneEmoji', () => {
it('returns true with a string with only one emoji', () => {
expect(isStringWithOnlyOneEmoji(':wave:')).toBeTruthy()
expect(isStringWithOnlyOneEmoji(':smile:')).toBeTruthy()
})
it('returns false with a string with multiple emoji or with text', () => {
expect(isStringWithOnlyOneEmoji(':wave: :smile:')).toBeFalsy()
expect(isStringWithOnlyOneEmoji(':wave: some text')).toBeFalsy()
expect(isStringWithOnlyOneEmoji('some text :wave:')).toBeFalsy()
})
it('returns false with a string without emoji', () => {
expect(isStringWithOnlyOneEmoji('some text')).toBeFalsy()
})
})

View File

@ -1,15 +0,0 @@
import { render } from '@testing-library/react'
import { ErrorPage } from '.'
describe('<ErrorPage />', () => {
it('should render the message and statusCode', () => {
const messageContent = 'message content'
const statusCode = 404
const { getByText } = render(
<ErrorPage statusCode={statusCode} message={messageContent} />
)
expect(getByText(messageContent)).toBeInTheDocument()
expect(getByText(statusCode)).toBeInTheDocument()
})
})

View File

@ -1 +0,0 @@
export * from './ErrorPage'

View File

@ -1,16 +0,0 @@
import { render } from '@testing-library/react'
import { Footer } from '.'
describe('<Footer />', () => {
it('should render with appropriate link tag version', () => {
const version = '1.0.0'
const { getByText } = render(<Footer version={version} />)
const versionLink = getByText(`website v${version}`) as HTMLAnchorElement
expect(getByText('Thream')).toBeInTheDocument()
expect(versionLink).toBeInTheDocument()
expect(versionLink.href).toEqual(
`https://github.com/Thream/website/releases/tag/v${version}`
)
})
})

View File

@ -8,6 +8,7 @@ export const VersionLink: React.FC<VersionLinkProps> = (props) => {
return (
<a
data-cy={`version-link-${repository}`}
className='text-green-800 hover:underline dark:text-green-400'
href={`https://github.com/Thream/${repository}/releases/tag/v${version}`}
target='_blank'

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { ScrollableBody } from './ScrollableBody'
describe('<ScrollableBody />', () => {
it('should render successfully', () => {
const { baseElement } = render(<ScrollableBody />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1 +0,0 @@
export * from './ScrollableBody'

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { Button } from '.'
describe('<Button />', () => {
it('should render', () => {
const { getByText } = render(<Button>Submit</Button>)
expect(getByText('Submit')).toBeInTheDocument()
})
})

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { Checkbox } from './Checkbox'
describe('<Checkbox />', () => {
it('should render successfully', () => {
const { baseElement } = render(<Checkbox label='Checkbox' />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { Divider } from '.'
describe('<Divider />', () => {
it('should render successfully', () => {
const { baseElement } = render(<Divider />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1,34 +0,0 @@
import { render } from '@testing-library/react'
import { FormState } from '.'
describe('<FormState />', () => {
it('should return nothing if the state is idle', () => {
const { container } = render(<FormState state='idle' />)
expect(container.innerHTML.length).toEqual(0)
})
it('should return nothing if the message is null', () => {
const { container } = render(<FormState state='error' />)
expect(container.innerHTML.length).toEqual(0)
})
it('should render the <Loader /> if state is loading', () => {
const { getByTestId } = render(<FormState state='loading' />)
expect(getByTestId('loader')).toBeInTheDocument()
})
it('should render the success message if state is success', () => {
const message = 'Success Message'
const { getByText } = render(
<FormState state='success' message={message} />
)
expect(getByText(message)).toBeInTheDocument()
})
it('should render the error message if state is error', () => {
const message = 'Error Message'
const { getByText } = render(<FormState state='error' message={message} />)
expect(getByText(message)).toBeInTheDocument()
})
})

View File

@ -16,7 +16,7 @@ export const FormState: React.FC<FormStateProps> = (props) => {
if (state === 'loading') {
return (
<div data-testid='loader' className='mt-8 flex justify-center'>
<div data-cy='loader' className='mt-8 flex justify-center'>
<Loader />
</div>
)

View File

@ -1,15 +0,0 @@
import { render } from '@testing-library/react'
import { CogIcon } from '@heroicons/react/solid'
import { IconButton } from './IconButton'
describe('<IconButton />', () => {
it('should render successfully', () => {
const { baseElement } = render(
<IconButton className='h-10 w-10'>
<CogIcon />
</IconButton>
)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { IconLink } from './IconLink'
describe('<IconLink />', () => {
it('should render successfully', () => {
const { baseElement } = render(<IconLink href='' />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1,52 +0,0 @@
import { render, fireEvent } from '@testing-library/react'
import { Input, getInputType } from '.'
describe('<Input />', () => {
it('should render the label', () => {
const labelContent = 'label content'
const { getByText } = render(<Input label={labelContent} />)
expect(getByText(labelContent)).toBeInTheDocument()
})
it('should not render forgot password link', () => {
const { queryByTestId } = render(
<Input type='text' label='content' showForgotPassword />
)
const forgotPasswordLink = queryByTestId('forgot-password-link')
expect(forgotPasswordLink).not.toBeInTheDocument()
})
it('should render forgot password link', () => {
const { queryByTestId } = render(
<Input type='password' label='content' showForgotPassword />
)
const forgotPasswordLink = queryByTestId('forgot-password-link')
expect(forgotPasswordLink).toBeInTheDocument()
})
it('should not render the eye icon if the input is not of type "password"', () => {
const { queryByTestId } = render(<Input type='text' label='content' />)
const passwordEye = queryByTestId('password-eye')
expect(passwordEye).not.toBeInTheDocument()
})
it('should handlePassword with eye icon', async () => {
const { findByTestId } = render(<Input type='password' label='content' />)
const passwordEye = await findByTestId('password-eye')
const input = await findByTestId('input')
expect(input).toHaveAttribute('type', 'password')
fireEvent.click(passwordEye)
expect(input).toHaveAttribute('type', 'text')
})
})
describe('getInputType', () => {
it('should return `text`', () => {
expect(getInputType('password')).toEqual('text')
})
it('should return `password`', () => {
expect(getInputType('text')).toEqual('password')
})
})

View File

@ -47,7 +47,7 @@ export const Input: React.FC<InputProps> = (props) => {
<Link href='/authentication/forgot-password'>
<a
className='text-center font-headline text-xs text-green-800 hover:underline dark:text-green-400 sm:text-sm'
data-testid='forgot-password-link'
data-cy='forgot-password-link'
>
{t('authentication:forgot-password')}
</a>
@ -56,7 +56,6 @@ export const Input: React.FC<InputProps> = (props) => {
</div>
<div className='relative mt-0'>
<input
data-testid='input'
data-cy={`input-${name ?? 'name'}`}
className='h-11 w-full rounded-lg border border-transparent bg-[#f1f1f1] px-3 font-paragraph leading-10 text-[#2a2a2a] caret-green-600 focus:border focus:shadow-green focus:outline-none'
{...rest}
@ -66,7 +65,7 @@ export const Input: React.FC<InputProps> = (props) => {
/>
{type === 'password' && (
<div
data-testid='password-eye'
data-cy='password-eye'
onClick={handlePassword}
className='password-eye absolute cursor-pointer bg-[#f1f1f1] bg-cover'
/>

View File

@ -1,20 +0,0 @@
import { render } from '@testing-library/react'
import { Loader } from '.'
describe('<Loader />', () => {
it('should render with correct width and height', async () => {
const size = 20
const { findByTestId } = render(<Loader width={size} height={size} />)
const progressSpinner = await findByTestId('progress-spinner')
expect(progressSpinner).toHaveStyle(`width: ${size}px`)
expect(progressSpinner).toHaveStyle(`height: ${size}px`)
})
it('should render with default width and height', async () => {
const { findByTestId } = render(<Loader />)
const progressSpinner = await findByTestId('progress-spinner')
expect(progressSpinner).toHaveStyle('width: 50px')
expect(progressSpinner).toHaveStyle('height: 50px')
})
})

View File

@ -9,7 +9,7 @@ export const Loader: React.FC<LoaderProps> = (props) => {
return (
<div className={props.className}>
<div data-testid='progress-spinner' className='progress-spinner'>
<div data-cy='progress-spinner' className='progress-spinner'>
<svg className='progress-spinner-svg' viewBox='25 25 50 50'>
<circle
className='progress-spinner-circle'

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { Main } from '.'
describe('<Main />', () => {
it('should render successfully', () => {
const { baseElement } = render(<Main />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -1,23 +0,0 @@
import { render } from '@testing-library/react'
import { SocialMedia, SocialMediaButton } from '.'
describe('<SocialMediaButton />', () => {
it('should render the social media', async () => {
const socialMedia: SocialMedia = 'Discord'
const { findByAltText } = render(
<SocialMediaButton socialMedia={socialMedia} />
)
const socialMediaButton = await findByAltText(socialMedia)
expect(socialMediaButton).toBeInTheDocument()
})
it('should render with a black text color with Google social media', async () => {
const socialMedia: SocialMedia = 'Google'
const { findByTestId } = render(
<SocialMediaButton socialMedia={socialMedia} />
)
const button = await findByTestId('social-media-button')
expect(button).toHaveStyle('color: #000')
})
})

View File

@ -54,7 +54,6 @@ export const SocialMediaButton: React.FC<SocialMediaButtonProps> = (props) => {
return (
<>
<button
data-testid='social-media-button'
{...rest}
className={classNames(className, 'button', givenClassName)}
>

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { Textarea } from './Textarea'
describe('<Textarea />', () => {
it('should render successfully', () => {
const { baseElement } = render(<Textarea label='Textarea' />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -6,6 +6,7 @@ import { useAuthentication } from '../tools/authentication'
import { Channel, ChannelWithDefaultChannelId } from '../models/Channel'
import { GuildsChannelsPath } from '../components/Application'
import { handleSocketData, SocketData } from '../tools/handleSocketData'
import { CacheKey, CHANNELS_CACHE_KEY } from '../tools/cache'
export interface Channels {
channels: Channel[]
@ -27,6 +28,8 @@ export const ChannelsProvider: React.FC<
const router = useRouter()
const { authentication } = useAuthentication()
const cacheKey: CacheKey = `${path.guildId}-${CHANNELS_CACHE_KEY}`
const {
items: channels,
hasMore,
@ -35,14 +38,15 @@ export const ChannelsProvider: React.FC<
setItems
} = usePagination<Channel>({
api: authentication.api,
url: `/guilds/${path.guildId}/channels`
url: `/guilds/${path.guildId}/channels`,
cacheKey
})
useEffect(() => {
authentication.socket.on(
authentication?.socket?.on(
'channels',
async (data: SocketData<ChannelWithDefaultChannelId>) => {
handleSocketData({ data, setItems })
handleSocketData({ data, setItems, cacheKey })
if (data.action === 'delete') {
await router.push(
`/application/${path.guildId}/${data.item.defaultChannelId}`
@ -52,9 +56,9 @@ export const ChannelsProvider: React.FC<
)
return () => {
authentication.socket.off('channels')
authentication?.socket?.off('channels')
}
}, [authentication.socket, path.guildId, router, setItems])
}, [authentication.socket, path.guildId, router, setItems, cacheKey])
useEffect(() => {
resetPagination()

View File

@ -47,7 +47,7 @@ export const GuildMemberProvider: React.FC<
}, [path, authentication.api])
useEffect(() => {
authentication.socket.on(
authentication?.socket?.on(
'guilds',
async (data: SocketData<GuildWithDefaultChannelId>) => {
if (data.item.id === path.guildId) {
@ -72,7 +72,7 @@ export const GuildMemberProvider: React.FC<
)
return () => {
authentication.socket.off('guilds')
authentication?.socket?.off('guilds')
}
}, [authentication.socket, path.guildId, router])

View File

@ -4,6 +4,7 @@ import { NextPage, usePagination } from '../hooks/usePagination'
import { useAuthentication } from '../tools/authentication'
import { GuildWithDefaultChannelId } from '../models/Guild'
import { handleSocketData, SocketData } from '../tools/handleSocketData'
import { GUILDS_CACHE_KEY } from '../tools/cache'
export interface Guilds {
guilds: GuildWithDefaultChannelId[]
@ -29,19 +30,20 @@ export const GuildsProvider: React.FC<React.PropsWithChildren<{}>> = (
setItems
} = usePagination<GuildWithDefaultChannelId>({
api: authentication.api,
url: '/guilds'
url: '/guilds',
cacheKey: GUILDS_CACHE_KEY
})
useEffect(() => {
authentication.socket.on(
authentication?.socket?.on(
'guilds',
(data: SocketData<GuildWithDefaultChannelId>) => {
handleSocketData({ data, setItems })
handleSocketData({ data, setItems, cacheKey: GUILDS_CACHE_KEY })
}
)
return () => {
authentication.socket.off('guilds')
authentication?.socket?.off('guilds')
}
}, [authentication.socket, setItems])

View File

@ -6,6 +6,7 @@ import { MemberWithPublicUser } from '../models/Member'
import { GuildsChannelsPath } from '../components/Application'
import { handleSocketData, SocketData } from '../tools/handleSocketData'
import { User } from '../models/User'
import { CacheKey, MEMBERS_CACHE_KEY } from '../tools/cache'
export interface Members {
members: MemberWithPublicUser[]
@ -27,6 +28,8 @@ export const MembersProviders: React.FC<
const { authentication } = useAuthentication()
const cacheKey: CacheKey = `${path.guildId}-${MEMBERS_CACHE_KEY}`
const {
items: members,
hasMore,
@ -35,18 +38,19 @@ export const MembersProviders: React.FC<
setItems
} = usePagination<MemberWithPublicUser>({
api: authentication.api,
url: `/guilds/${path.guildId}/members`
url: `/guilds/${path.guildId}/members`,
cacheKey
})
useEffect(() => {
authentication.socket.on(
authentication?.socket?.on(
'members',
(data: SocketData<MemberWithPublicUser>) => {
handleSocketData({ data, setItems })
handleSocketData({ data, setItems, cacheKey })
}
)
authentication.socket.on('users', (data: SocketData<User>) => {
authentication?.socket?.on('users', (data: SocketData<User>) => {
setItems((oldItems) => {
const newItems = [...oldItems]
switch (data.action) {
@ -65,10 +69,10 @@ export const MembersProviders: React.FC<
})
return () => {
authentication.socket.off('members')
authentication.socket.off('users')
authentication?.socket?.off('members')
authentication?.socket?.off('users')
}
}, [authentication.socket, setItems])
}, [authentication.socket, setItems, cacheKey])
useEffect(() => {
resetPagination()

View File

@ -5,6 +5,7 @@ import { useAuthentication } from '../tools/authentication'
import { MessageWithMember } from '../models/Message'
import { GuildsChannelsPath } from '../components/Application'
import { handleSocketData, SocketData } from '../tools/handleSocketData'
import { CacheKey, MESSAGES_CACHE_KEY } from '../tools/cache'
export interface Messages {
messages: MessageWithMember[]
@ -25,6 +26,8 @@ export const MessagesProvider: React.FC<
const { path, children } = props
const { authentication, user } = useAuthentication()
const cacheKey: CacheKey = `${path.channelId}-${MESSAGES_CACHE_KEY}`
const {
items: messages,
hasMore,
@ -34,11 +37,12 @@ export const MessagesProvider: React.FC<
} = usePagination<MessageWithMember>({
api: authentication.api,
url: `/channels/${path.channelId}/messages`,
inverse: true
inverse: true,
cacheKey
})
useEffect(() => {
authentication.socket.on(
authentication?.socket?.on(
'messages',
(data: SocketData<MessageWithMember>) => {
if (data.item.channelId === path.channelId) {
@ -48,7 +52,7 @@ export const MessagesProvider: React.FC<
const isAtBottom =
messagesDiv.scrollHeight - messagesDiv.scrollTop <=
messagesDiv.clientHeight
handleSocketData({ data, setItems })
handleSocketData({ data, setItems, cacheKey })
if (
data.action === 'create' &&
(isAtBottom || data.item.member.userId === user.id)
@ -60,9 +64,9 @@ export const MessagesProvider: React.FC<
)
return () => {
authentication.socket.off('messages')
authentication?.socket?.off('messages')
}
}, [authentication.socket, setItems, path, user.id])
}, [authentication.socket, setItems, path, user.id, cacheKey])
useEffect(() => {
resetPagination()

72
cypress.config.ts Normal file
View File

@ -0,0 +1,72 @@
import path from 'node:path'
import { defineConfig } from 'cypress'
import { getLocal } from 'mockttp'
import type { Mockttp } from 'mockttp'
import { API_DEFAULT_PORT } from './tools/api'
import { Handlers, Method } from './cypress/fixtures/handler'
const UPLOADS_FIXTURES_DIRECTORY = path.join(
process.cwd(),
'cypress',
'fixtures',
'uploads'
)
let server: Mockttp | null = null
export default defineConfig({
fixturesFolder: false,
video: false,
downloadsFolder: undefined,
screenshotOnRunFailure: false,
e2e: {
baseUrl: 'http://localhost:3000',
supportFile: false,
setupNodeEvents(on, config) {
on('task', {
async startMockServer(handlers: Handlers): Promise<null> {
server = getLocal({
cors: true
})
await server.start(API_DEFAULT_PORT)
for (const handler of handlers) {
const { isFile = false } = handler.response
const method = handler.method.toLowerCase() as Lowercase<Method>
if (isFile) {
await server[method](handler.url).thenFromFile(
handler.response.statusCode,
path.join(UPLOADS_FIXTURES_DIRECTORY, ...handler.response.body)
)
} else {
await server[method](handler.url).thenJson(
handler.response.statusCode,
handler.response.body
)
}
}
return null
},
async stopMockServer(): Promise<null> {
if (server != null) {
await server.stop()
server = null
}
return null
}
})
return config
}
},
component: {
devServer: {
framework: 'next',
bundler: 'webpack'
}
}
})

View File

@ -1,6 +0,0 @@
{
"baseUrl": "http://localhost:3000",
"supportFile": false,
"video": false,
"screenshotOnRunFailure": false
}

View File

@ -0,0 +1,18 @@
import { isStringWithOnlyOneEmoji } from '../../../../components/Emoji/isStringWithOnlyOneEmoji'
describe('components/Emoji/isStringWithOnlyOneEmoji', () => {
it('returns true with a string with only one emoji', () => {
expect(isStringWithOnlyOneEmoji(':wave:')).equal(true)
expect(isStringWithOnlyOneEmoji(':smile:')).equal(true)
})
it('returns false with a string with multiple emoji or with text', () => {
expect(isStringWithOnlyOneEmoji(':wave: :smile:')).equal(false)
expect(isStringWithOnlyOneEmoji(':wave: some text')).equal(false)
expect(isStringWithOnlyOneEmoji('some text :wave:')).equal(false)
})
it('returns false with a string without emoji', () => {
expect(isStringWithOnlyOneEmoji('some text')).equal(false)
})
})

View File

@ -0,0 +1,16 @@
import { Footer } from '../../../components/Footer'
describe('<Footer />', () => {
it('should render with appropriate link tag version', () => {
const version = '1.0.0'
cy.mount(<Footer version={version} />)
cy.contains('Thream')
.get('[data-cy=version-link-website]')
.should('have.text', `website v${version}`)
.should(
'have.attr',
'href',
`https://github.com/Thream/website/releases/tag/v${version}`
)
})
})

View File

@ -0,0 +1,35 @@
import { FormState } from '../../../../components/design/FormState'
describe('<FormState />', () => {
it('should return nothing if the state is idle', () => {
cy.mount(<FormState state='idle' />)
.get('[data-cy-root]')
.should('be.empty')
})
it('should return nothing if the message is null', () => {
cy.mount(<FormState state='error' />)
.get('[data-cy-root]')
.should('be.empty')
})
it('should render the <Loader /> if state is loading', () => {
cy.mount(<FormState state='loading' />)
.get('[data-cy=loader]')
.should('be.visible')
})
it('should render the success message if state is success', () => {
const message = 'Success Message'
cy.mount(<FormState state='success' message={message} id='success' />)
.get('#success')
.contains(message)
})
it('should render the error message if state is error', () => {
const message = 'Error Message'
cy.mount(<FormState state='error' message={message} id='error' />)
.get('#error')
.contains(message)
})
})

View File

@ -0,0 +1,48 @@
import { Input, getInputType } from '../../../../components/design/Input'
describe('<Input />', () => {
it('should render the label', () => {
const labelContent = 'label content'
cy.mount(<Input label={labelContent} />)
.get('label')
.should('have.text', labelContent)
})
it('should not render forgot password link', () => {
cy.mount(<Input type='text' label='content' showForgotPassword />)
.get('[data-cy=forgot-password-link]')
.should('not.exist')
})
it('should render forgot password link', () => {
cy.mount(<Input type='password' label='content' showForgotPassword />)
.get('[data-cy=forgot-password-link]')
.should('exist')
})
it('should not render the eye icon if the input is not of type "password"', () => {
cy.mount(<Input type='text' label='content' />)
.get('[data-cy=password-eye]')
.should('not.exist')
})
it('should handlePassword with eye icon', async () => {
cy.mount(<Input type='password' label='content' />)
.get('input')
.should('have.attr', 'type', 'password')
.get('[data-cy=password-eye]')
.click()
.get('input')
.should('have.attr', 'type', 'text')
})
describe('getInputType', () => {
it('should return `text`', () => {
expect(getInputType('password')).equal('text')
})
it('should return `password`', () => {
expect(getInputType('text')).equal('password')
})
})
})

View File

@ -1,6 +1,6 @@
import type { ErrorObject } from 'ajv'
import { getErrorTranslationKey } from './getErrorTranslationKey'
import { getErrorTranslationKey } from '../../../../hooks/useForm/getErrorTranslationKey'
const errorObject: ErrorObject = {
instancePath: '/path',
@ -16,7 +16,7 @@ describe('hooks/useForm/getErrorTranslationKey', () => {
...errorObject,
keyword: 'unknownkeyword'
})
).toEqual('errors:invalid')
).equal('errors:invalid')
})
it('returns `errors:invalid` with format != email', () => {
@ -26,7 +26,7 @@ describe('hooks/useForm/getErrorTranslationKey', () => {
keyword: 'format',
params: { format: 'email' }
})
).toEqual('errors:email')
).equal('errors:email')
})
it('returns `errors:email` with format = email', () => {
@ -36,7 +36,7 @@ describe('hooks/useForm/getErrorTranslationKey', () => {
keyword: 'format',
params: { format: 'email' }
})
).toEqual('errors:email')
).equal('errors:email')
})
it('returns `errors:required` with minLength and limit = 1', () => {
@ -46,7 +46,7 @@ describe('hooks/useForm/getErrorTranslationKey', () => {
keyword: 'minLength',
params: { limit: 1 }
})
).toEqual('errors:required')
).equal('errors:required')
})
it('returns `errors:minLength` with minLength and limit > 1', () => {
@ -56,7 +56,7 @@ describe('hooks/useForm/getErrorTranslationKey', () => {
keyword: 'minLength',
params: { limit: 5 }
})
).toEqual('errors:minLength')
).equal('errors:minLength')
})
it('returns `errors:maxLength` with maxLength', () => {
@ -66,6 +66,6 @@ describe('hooks/useForm/getErrorTranslationKey', () => {
keyword: 'maxLength',
params: { limit: 5 }
})
).toEqual('errors:maxLength')
).equal('errors:maxLength')
})
})

View File

@ -1,6 +1,6 @@
import { Type } from '@sinclair/typebox'
import { handleCheckboxBoolean } from './handleCheckboxBoolean'
import { handleCheckboxBoolean } from '../../../../hooks/useForm/handleCheckboxBoolean'
const schema = Type.Object({
myBoolean: Type.Boolean(),
@ -14,7 +14,7 @@ describe('hooks/useForm/handleCheckboxBoolean', () => {
myString: 'on'
}
const result = handleCheckboxBoolean(object, schema)
expect(result).toEqual({
expect(result).deep.equal({
myBoolean: true,
myString: 'on'
})

View File

@ -1,6 +1,6 @@
import { replaceEmptyStringInObjectToNull } from './replaceEmptyStringInObjectToNull'
import { replaceEmptyStringInObjectToNull } from '../../../../hooks/useForm/replaceEmptyStringInObjectToNull'
describe('tools/utils/replaceEmptyStringInObjectToNull', () => {
describe('hooks/useForm/replaceEmptyStringInObjectToNull', () => {
it('should replace empty string in object to null except for required properties', () => {
expect(
replaceEmptyStringInObjectToNull(
@ -11,7 +11,7 @@ describe('tools/utils/replaceEmptyStringInObjectToNull', () => {
},
['baz']
)
).toEqual({
).deep.equal({
foo: null,
bar: 'bar',
baz: ''

View File

@ -0,0 +1,10 @@
import { capitalize } from '../../../../tools/utils/capitalize'
describe('tools/utils/capitalize', () => {
it('should capitalize the first letter of a string', () => {
expect(capitalize('hello')).equal('Hello')
expect(capitalize('HeLlo')).equal('HeLlo')
expect(capitalize('member(s)')).equal('Member(s)')
expect(capitalize('Member(s)')).equal('Member(s)')
})
})

View File

@ -49,3 +49,5 @@ describe('Common > Header', () => {
})
})
})
export {}

View File

@ -45,3 +45,5 @@ describe('Common > application/authentication', () => {
}
})
})
export {}

View File

@ -7,3 +7,5 @@ describe('Page > /404', () => {
cy.get('[data-cy=status-code]').contains('404')
})
})
export {}

View File

@ -7,3 +7,5 @@ describe('Page > /500', () => {
cy.get('[data-cy=status-code]').contains('500')
})
})
export {}

View File

@ -267,3 +267,5 @@ describe('Pages > /application/[guildId]/[channelId]', () => {
.should('eq', '/404')
})
})
export {}

View File

@ -132,3 +132,5 @@ describe('Pages > /application/[guildId]/[channelId]/settings', () => {
.should('eq', '/404')
})
})
export {}

View File

@ -72,3 +72,5 @@ describe('Pages > /application/[guildId]/channels/create', () => {
.should('eq', '/404')
})
})
export {}

View File

@ -102,3 +102,5 @@ describe('Pages > /application/[guildId]/settings', () => {
.should('eq', '/404')
})
})
export {}

View File

@ -42,3 +42,5 @@ describe('Pages > /application/guilds/create', () => {
cy.get('#message').should('have.text', 'Error: Internal Server Error.')
})
})
export {}

View File

@ -75,6 +75,8 @@ describe('Pages > /application/guilds/join', () => {
)
cy.visit('/application/guilds/join')
cy.get('.guilds-public-list').children().should('have.length', 1)
cy.get('[data-testid=progress-spinner]').should('be.visible')
cy.get('[data-cy=progress-spinner]').should('be.visible')
})
})
export {}

View File

@ -30,3 +30,5 @@ describe('Pages > /application', () => {
.should('eq', '/application/guilds/join')
})
})
export {}

View File

@ -33,3 +33,5 @@ describe('Pages > /application/users/[userId]', () => {
.should('eq', '/404')
})
})
export {}

View File

@ -35,3 +35,5 @@ describe('Pages > /authentication/forgot-password', () => {
)
})
})
export {}

View File

@ -46,3 +46,5 @@ describe('Pages > /authentication/reset-password', () => {
)
})
})
export {}

View File

@ -53,3 +53,5 @@ describe('Pages > /authentication/signin', () => {
cy.get('#error-password').should('not.exist')
})
})
export {}

View File

@ -83,3 +83,5 @@ describe('Pages > /authentication/signup', () => {
)
})
})
export {}

View File

@ -10,3 +10,5 @@ describe('Page > /', () => {
.should('eq', '/authentication/signup')
})
})
export {}

View File

@ -1,66 +0,0 @@
import path from 'node:path'
import { getLocal } from 'mockttp'
import { API_DEFAULT_PORT } from '../../tools/api'
/// <reference types="cypress" />
/**
* @typedef {import('../fixtures/handler').Method} Method
*/
/** @type {import('mockttp').Mockttp | null} */
let server = null
const UPLOADS_FIXTURES_DIRECTORY = path.join(
process.cwd(),
'cypress',
'fixtures',
'uploads'
)
/**
* @type {Cypress.PluginConfig}
*/
module.exports = (on, config) => {
on('task', {
/**
* @param {import('../fixtures/handler').Handlers} handlers
*/
async startMockServer(handlers) {
server = getLocal({
cors: true
})
await server.start(API_DEFAULT_PORT)
for (const handler of handlers) {
const { isFile = false } = handler.response
const method = /** @type {Lowercase<Method>} */ (
handler.method.toLowerCase()
)
if (isFile) {
await server[method](handler.url).thenFromFile(
handler.response.statusCode,
path.join(UPLOADS_FIXTURES_DIRECTORY, ...handler.response.body)
)
} else {
await server[method](handler.url).thenJson(
handler.response.statusCode,
handler.response.body
)
}
}
return null
},
async stopMockServer() {
if (server != null) {
await server.stop()
server = null
}
return null
}
})
return config
}

View File

@ -0,0 +1,3 @@
/// <reference types="cypress" />
export {}

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>Components App</title>
<!-- Used by Next.js to inject CSS. -->
<div id="__next_css__DO_NOT_USE__"></div>
</head>
<body>
<div data-cy-root></div>
</body>
</html>

View File

@ -0,0 +1,14 @@
import { mount } from 'cypress/react'
import './commands'
import '../../styles/global.css'
declare global {
namespace Cypress {
interface Chainable {
mount: typeof mount
}
}
}
Cypress.Commands.add('mount', mount)

View File

@ -1,9 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"types": ["cypress"],
"isolatedModules": false
},
"include": ["../node_modules/cypress", "./**/*.ts"]
}

View File

@ -1,10 +0,0 @@
import { render } from '@testing-library/react'
import { {{ properCase name }} } from './{{ properCase name }}'
describe('<{{ properCase name }} />', () => {
it('should render', () => {
const { baseElement } = render(<{{ properCase name }} />)
expect(baseElement).toBeTruthy()
})
})

View File

@ -17,16 +17,6 @@ exports.componentGenerator = () => {
}
],
actions: [
{
type: 'add',
path: 'components/{{folder}}/{{properCase name}}/{{properCase name}}.stories.tsx',
templateFile: 'generators/component/Component.stories.tsx.hbs'
},
{
type: 'add',
path: 'components/{{folder}}/{{properCase name}}/{{properCase name}}.test.tsx',
templateFile: 'generators/component/Component.test.tsx.hbs'
},
{
type: 'add',
path: 'components/{{folder}}/{{properCase name}}/{{properCase name}}.tsx',

View File

@ -2,6 +2,11 @@ import { useState, useRef, useCallback } from 'react'
import { AxiosInstance } from 'axios'
import { FetchState } from './useFetchState'
import {
CacheKey,
getPaginationCache,
savePaginationCache
} from '../tools/cache'
export interface Query {
[key: string]: string
@ -13,6 +18,11 @@ export interface UsePaginationOptions {
api: AxiosInstance
url: string
inverse?: boolean
cacheKey?: CacheKey
}
export interface PaginationItem {
id: number
}
export type SetItems<T> = React.Dispatch<React.SetStateAction<T[]>>
@ -25,16 +35,25 @@ export interface UsePaginationResult<T> {
setItems: SetItems<T>
}
export const usePagination = <T extends { id: number }>(
export const usePagination = <T extends PaginationItem>(
options: UsePaginationOptions
): UsePaginationResult<T> => {
const { api, url, inverse = false } = options
const { api, url, inverse = false, cacheKey } = options
const [items, setItems] = useState<T[]>([])
const [hasMore, setHasMore] = useState(true)
const fetchState = useRef<FetchState>('idle')
const afterId = useRef<number | null>(null)
const updateAfterId = (newItems: T[]): void => {
if (!inverse) {
afterId.current =
newItems.length > 0 ? newItems[newItems.length - 1].id : null
} else {
afterId.current = newItems.length > 0 ? newItems[0].id : null
}
}
const nextPageAsync: NextPageAsync = useCallback(
async (query) => {
if (fetchState.current !== 'idle') {
@ -49,19 +68,22 @@ export const usePagination = <T extends { id: number }>(
const { data: newItems } = await api.get<T[]>(
`${url}?${searchParameters.toString()}`
)
if (!inverse) {
afterId.current =
newItems.length > 0 ? newItems[newItems.length - 1].id : null
} else {
afterId.current = newItems.length > 0 ? newItems[0].id : null
}
updateAfterId(newItems)
setItems((oldItems) => {
return inverse ? [...newItems, ...oldItems] : [...oldItems, ...newItems]
const updatedItems = inverse
? [...newItems, ...oldItems]
: [...oldItems, ...newItems]
if (cacheKey != null) {
savePaginationCache(cacheKey, updatedItems)
}
return updatedItems
})
setHasMore(newItems.length > 0)
fetchState.current = 'idle'
},
[api, url, inverse]
// eslint-disable-next-line react-hooks/exhaustive-deps -- We don't want infinite loops with updateAfterId
[api, url, inverse, cacheKey]
)
const nextPage: NextPage = useCallback(
@ -80,9 +102,17 @@ export const usePagination = <T extends { id: number }>(
)
const resetPagination = useCallback((): void => {
afterId.current = null
setItems([])
}, [])
if (cacheKey == null) {
afterId.current = null
setItems([])
} else {
const newItems = getPaginationCache<T>(cacheKey)
setItems(newItems)
updateAfterId(newItems)
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- We don't want infinite loops with updateAfterId
}, [cacheKey])
return { items, hasMore, nextPage, resetPagination, setItems }
}

View File

@ -1,14 +0,0 @@
const nextJest = require('next/jest')
const createJestConfig = nextJest()
const customJestConfig = {
moduleDirectories: ['node_modules', './'],
modulePathIgnorePatterns: ['<rootDir>/cypress'],
testEnvironment: 'jsdom',
setupFilesAfterEnv: [
'@testing-library/jest-dom/extend-expect',
'@testing-library/react'
]
}
module.exports = createJestConfig(customJestConfig)

View File

@ -1,10 +1,13 @@
const nextPWA = require('next-pwa')
const nextPWA = require('next-pwa')({
disable: process.env.NODE_ENV !== 'production',
dest: 'public'
})
const nextTranslate = require('next-translate')
const { createSecureHeaders } = require('next-secure-headers')
/** @type {import("next").NextConfig} */
module.exports = nextTranslate(
nextPWA({
reactStrictMode: false,
images: {
domains: [
'api.thream.divlo.fr',
@ -12,38 +15,6 @@ module.exports = nextTranslate(
'file-uploads-api.thream.divlo.fr',
...(process.env.NODE_ENV !== 'production' ? ['localhost'] : [])
]
},
reactStrictMode: true,
pwa: {
disable: process.env.NODE_ENV !== 'production',
dest: 'public'
},
headers() {
return [
{
source: '/:path*',
headers: createSecureHeaders({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
"'self'",
'data:',
"'unsafe-eval'",
"'unsafe-inline'"
],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ['*', 'data:', 'blob:'],
mediaSrc: ['*', 'data:', 'blob:'],
connectSrc: '*',
objectSrc: "'none'",
fontSrc: "'self'",
baseURI: "'none'"
}
}
})
}
]
}
})
)

11062
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "@thream/website",
"version": "1.1.0",
"version": "1.1.1",
"private": true,
"repository": {
"type": "git",
@ -18,34 +18,35 @@
"generate": "plop",
"lint:commit": "commitlint",
"lint:editorconfig": "editorconfig-checker",
"lint:markdown": "markdownlint \"**/*.md\" --dot --ignore-path \".gitignore\"",
"lint:typescript": "eslint \"**/*.{js,jsx,ts,tsx}\"",
"lint:markdown": "markdownlint-cli2",
"lint:typescript": "eslint \"**/*.{js,jsx,ts,tsx}\" --ignore-path \".gitignore\"",
"lint:prettier": "prettier \".\" --check",
"lint:staged": "lint-staged",
"test:unit": "jest",
"test:unit": "cypress run --component",
"test:html-w3c-validator": "start-server-and-test \"start\" \"http://localhost:3000\" \"html-w3c-validator\"",
"test:lighthouse": "lhci autorun",
"test:e2e": "start-server-and-test \"start\" \"http://localhost:3000\" \"cypress run\"",
"test:e2e:dev": "start-server-and-test \"dev\" \"http://localhost:3000\" \"cypress open\"",
"test:dev": "start-server-and-test \"dev\" \"http://localhost:3000\" \"cypress open\"",
"release": "semantic-release",
"deploy": "vercel",
"postinstall": "husky install"
},
"dependencies": {
"@fontsource/montserrat": "4.5.11",
"@fontsource/roboto": "4.5.7",
"@fontsource/montserrat": "4.5.12",
"@fontsource/roboto": "4.5.8",
"@heroicons/react": "1.0.6",
"@sinclair/typebox": "0.23.5",
"@sinclair/typebox": "0.24.28",
"ajv": "8.11.0",
"ajv-formats": "2.1.1",
"axios": "0.26.1",
"classnames": "2.3.1",
"date-and-time": "2.4.0",
"date-and-time": "2.4.1",
"emoji-mart": "3.0.1",
"katex": "0.16.0",
"next": "12.2.0",
"next-pwa": "5.5.4",
"next": "12.2.5",
"next-pwa": "5.6.0",
"next-themes": "0.2.0",
"next-translate": "1.4.0",
"next-translate": "1.5.0",
"pretty-bytes": "6.0.0",
"react": "18.2.0",
"react-component-form": "3.0.1",
@ -64,7 +65,7 @@
"sharp": "0.30.7",
"socket.io-client": "4.5.1",
"unified": "10.1.2",
"unist-util-visit": "4.1.0",
"unist-util-visit": "4.1.1",
"universal-cookie": "4.0.4"
},
"devDependencies": {
@ -73,45 +74,41 @@
"@lhci/cli": "0.9.0",
"@saithodev/semantic-release-backmerge": "2.1.2",
"@semantic-release/git": "10.0.1",
"@testing-library/jest-dom": "5.16.4",
"@testing-library/react": "13.3.0",
"@types/emoji-mart": "3.0.9",
"@types/hast": "2.3.4",
"@types/jest": "27.5.1",
"@types/katex": "0.14.0",
"@types/node": "18.0.0",
"@types/react": "18.0.14",
"@types/node": "18.7.11",
"@types/react": "18.0.17",
"@types/react-responsive": "8.0.5",
"@types/react-syntax-highlighter": "15.5.2",
"@types/react-syntax-highlighter": "15.5.4",
"@types/unist": "2.0.6",
"@typescript-eslint/eslint-plugin": "5.30.0",
"@typescript-eslint/parser": "5.30.0",
"autoprefixer": "10.4.7",
"cypress": "9.6.1",
"@typescript-eslint/eslint-plugin": "5.34.0",
"@typescript-eslint/parser": "5.34.0",
"autoprefixer": "10.4.8",
"cypress": "10.6.0",
"editorconfig-checker": "4.0.2",
"eslint": "8.18.0",
"eslint-config-conventions": "2.0.0",
"eslint-config-next": "12.2.0",
"eslint": "8.22.0",
"eslint-config-conventions": "3.0.0",
"eslint-config-next": "12.2.5",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-prettier": "4.1.0",
"eslint-plugin-prettier": "4.2.1",
"eslint-plugin-promise": "6.0.0",
"eslint-plugin-unicorn": "42.0.0",
"eslint-plugin-unicorn": "43.0.2",
"html-w3c-validator": "1.2.0",
"husky": "8.0.1",
"jest": "27.5.1",
"lint-staged": "13.0.3",
"markdownlint-cli": "0.31.1",
"markdownlint-cli2": "0.5.1",
"mockttp": "2.7.0",
"next-secure-headers": "2.2.0",
"plop": "3.1.1",
"postcss": "8.4.14",
"postcss": "8.4.16",
"prettier": "2.7.1",
"prettier-plugin-tailwindcss": "0.1.11",
"semantic-release": "19.0.3",
"serve": "13.0.2",
"prettier-plugin-tailwindcss": "0.1.13",
"semantic-release": "19.0.5",
"serve": "14.0.1",
"start-server-and-test": "1.14.0",
"tailwindcss": "3.1.4",
"tailwindcss": "3.1.8",
"typescript": "4.7.4",
"vercel": "25.2.1"
"vercel": "28.1.2"
}
}

View File

@ -28,6 +28,9 @@ const Application = ({ Component, pageProps }: AppProps): JSX.Element => {
}
window.addEventListener('resize', appHeight)
appHeight()
return () => {
window.removeEventListener('resize', appHeight)
}
}, [lang])
return (

View File

@ -12,7 +12,7 @@ import { Input } from '../../components/design/Input'
import { Button } from '../../components/design/Button'
import { authenticationFromServerSide } from '../../tools/authentication'
import { AuthenticationForm } from '../../components/Authentication'
import { ScrollableBody } from '../../components/ScrollableBody/ScrollableBody'
import { ScrollableBody } from '../../components/ScrollableBody'
import { HandleSubmitCallback, useForm } from '../../hooks/useForm'
import { api } from '../../tools/api'
import { userSchema } from '../../models/User'

View File

@ -9,27 +9,36 @@ import { fetchRefreshToken } from './authenticationFromServerSide'
export class Authentication {
public tokens: Tokens
public accessTokenAge: number
public socket: Socket
public socket?: Socket
public api: AxiosInstance
constructor(tokens: Tokens) {
constructor(tokens: Tokens, disableSocketIO: boolean = false) {
this.tokens = tokens
this.accessTokenAge = Date.now()
this.socket = io(API_URL, {
auth: { token: `Bearer ${tokens.accessToken}` }
})
this.socket.on('connect_error', (error) => {
if (error.message.startsWith('Unauthorized')) {
fetchRefreshToken(this.tokens.refreshToken)
.then(({ accessToken }) => {
this.setAccessToken(accessToken)
})
.catch(async () => {
this.signout()
return await Promise.reject(error)
})
}
})
if (disableSocketIO || typeof window === 'undefined') {
this.socket = undefined
} else {
this.socket = io(API_URL, {
auth: { token: `Bearer ${tokens.accessToken}` }
})
this.socket.on('connect', () => {
console.log(
`Connected to socket with clientId: ${this.socket?.id ?? 'undefined'}`
)
})
this.socket.on('connect_error', (error) => {
if (error.message.startsWith('Unauthorized')) {
fetchRefreshToken(this.tokens.refreshToken)
.then(({ accessToken }) => {
this.setAccessToken(accessToken)
})
.catch(async () => {
this.signout()
return await Promise.reject(error)
})
}
})
}
this.api = axios.create({
baseURL: API_URL,
headers: {
@ -83,13 +92,14 @@ export class Authentication {
this.tokens.accessToken = accessToken
this.accessTokenAge = Date.now()
const token = `${this.tokens.type} ${this.tokens.accessToken}`
if (typeof this.socket.auth !== 'function') {
if (typeof this?.socket?.auth !== 'function' && this.socket != null) {
this.socket.auth.token = token
}
}
public signout(): void {
cookies.remove('refreshToken')
window.localStorage.clear()
window.location.href = '/authentication/signin'
}

View File

@ -25,7 +25,8 @@ export const AuthenticationProvider: React.FC<
const [user, setUser] = useState<UserCurrent>(props.authentication.user)
const authentication = useMemo(() => {
return new Authentication(props.authentication.tokens)
const disableSocketIO = typeof window === 'undefined'
return new Authentication(props.authentication.tokens, disableSocketIO)
// eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this memo once
}, [])
@ -33,7 +34,9 @@ export const AuthenticationProvider: React.FC<
useEffect(() => {
setLanguage(props.authentication.user.settings.language).catch(() => {})
setTheme(props.authentication.user.settings.theme)
return () => {
authentication?.socket?.disconnect()
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this effect once
}, [])

Some files were not shown because too many files have changed in this diff Show More