feat: create a guild (#1)

This commit is contained in:
Divlo
2021-10-26 16:38:55 +02:00
committed by GitHub
parent a0fa66e8f5
commit d8fab08585
45 changed files with 530 additions and 315 deletions

View File

@ -1,5 +1,6 @@
import { useState, useEffect, useMemo } from 'react'
import Image from 'next/image'
import useTranslation from 'next-translate/useTranslation'
import {
CogIcon,
PlusIcon,
@ -19,6 +20,7 @@ import { Guilds } from './Guilds/Guilds'
import { Divider } from '../design/Divider'
import { Members } from './Members'
import { useAuthentication } from 'utils/authentication'
import { API_URL } from 'utils/api'
export interface GuildsChannelsPath {
guildId: number
@ -37,6 +39,7 @@ export interface ApplicationProps {
export const Application: React.FC<ApplicationProps> = (props) => {
const { children, path } = props
const { t } = useTranslation()
const { user } = useAuthentication()
const [visibleSidebars, setVisibleSidebars] = useState({
@ -138,10 +141,10 @@ export const Application: React.FC<ApplicationProps> = (props) => {
return 'Join a Guild'
}
if (path === '/application/guilds/create') {
return 'Create a Guild'
return t('application:create-a-guild')
}
return 'Application'
}, [path])
}, [path, t])
useEffect(() => {
setMounted(true)
@ -193,7 +196,11 @@ export const Application: React.FC<ApplicationProps> = (props) => {
>
<Image
className='rounded-full'
src='/images/data/divlo.png'
src={
user.logo == null
? '/images/data/user-default.png'
: API_URL + user.logo
}
alt='logo'
width={48}
height={48}

View File

@ -0,0 +1,15 @@
import { Meta, Story } from '@storybook/react'
import { CreateGuild as Component } from './CreateGuild'
const Stories: Meta = {
title: 'CreateGuild',
component: Component
}
export default Stories
export const CreateGuild: Story = (arguments_) => {
return <Component {...arguments_} />
}
CreateGuild.args = {}

View File

@ -0,0 +1,82 @@
import { useRouter } from 'next/router'
import useTranslation from 'next-translate/useTranslation'
import { Form } from 'react-component-form'
import TextareaAutosize from 'react-textarea-autosize'
import { AxiosResponse } from 'axios'
import { useAuthentication } from '../../../utils/authentication'
import { HandleSubmitCallback, useForm } from '../../../hooks/useForm'
import { GuildComplete, guildSchema } from '../../../models/Guild'
import { Input } from '../../design/Input'
import { Main } from '../../design/Main'
import { Button } from '../../design/Button'
import { FormState } from '../../design/FormState'
export const CreateGuild: React.FC = () => {
const { t } = useTranslation()
const router = useRouter()
const { formState, message, errors, getErrorTranslation, handleSubmit } =
useForm({
validateSchemaObject: {
name: guildSchema.name,
description: guildSchema.description
}
})
const { authentication } = useAuthentication()
const onSubmit: HandleSubmitCallback = async (formData) => {
try {
const { data } = await authentication.api.post<
any,
AxiosResponse<{ guild: GuildComplete }>
>('/guilds', { name: formData.name, description: formData.description })
const guildId = data.guild.id
const channelId = data.guild.channels[0].id
await router.push(`/application/${guildId}/${channelId}`)
return null
} catch (error) {
return {
type: 'error',
value: 'errors:server-error'
}
}
}
return (
<Main>
<Form className='w-4/6 max-w-xs' onSubmit={handleSubmit(onSubmit)}>
<Input
type='text'
placeholder={t('common:name')}
name='name'
label={t('common:name')}
error={getErrorTranslation(errors.name)}
/>
<div className='flex flex-col'>
<div className='flex justify-between mt-6 mb-2'>
<label className='pl-1' htmlFor='description'>
Description
</label>
</div>
<div className='mt-0 relative'>
<TextareaAutosize
className='p-3 rounded-lg bg-[#f1f1f1] text-[#2a2a2a] caret-green-600 font-paragraph w-full focus:border focus:outline-none resize-none focus:shadow-green'
placeholder='Description...'
id='description'
name='description'
wrap='soft'
></TextareaAutosize>
</div>
</div>
<Button className='w-full mt-6' type='submit' data-cy='submit'>
{t('application:create')}
</Button>
</Form>
<FormState id='message' state={formState} message={message} />
</Main>
)
}

View File

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

View File

@ -1,5 +1,5 @@
import { Meta, Story } from '@storybook/react'
import { user, userSettings } from '../../cypress/fixtures/users/user'
import { user, userSettings } from '../../../cypress/fixtures/users/user'
import { UserProfile as Component, UserProfileProps } from './UserProfile'

View File

@ -1,6 +1,6 @@
import { render } from '@testing-library/react'
import { user, userSettings } from '../../cypress/fixtures/users/user'
import { user, userSettings } from '../../../cypress/fixtures/users/user'
import { UserProfile } from './UserProfile'

View File

@ -4,7 +4,7 @@ import classNames from 'classnames'
import useTranslation from 'next-translate/useTranslation'
import date from 'date-and-time'
import { UserPublic } from '../../models/User'
import { UserPublic } from '../../../models/User'
export interface UserProfileProps {
className?: string
@ -15,8 +15,6 @@ export interface UserProfileProps {
export const UserProfile: React.FC<UserProfileProps> = (props) => {
const { user, isOwner = false } = props
console.log(user)
const { t } = useTranslation()
const handleSubmitChanges = (

View File

@ -1,11 +1,7 @@
import { useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'
import useTranslation from 'next-translate/useTranslation'
import { useTheme } from 'next-themes'
import { Type } from '@sinclair/typebox'
import type { ErrorObject } from 'ajv'
import type { HandleForm } from 'react-component-form'
import axios from 'axios'
import { SocialMediaButton } from '../design/SocialMediaButton'
@ -13,26 +9,14 @@ import { Main } from '../design/Main'
import { Input } from '../design/Input'
import { Button } from '../design/Button'
import { FormState } from '../design/FormState'
import { useFormState } from '../../hooks/useFormState'
import { AuthenticationForm } from './'
import { userSchema } from '../../models/User'
import { ajv } from '../../utils/ajv'
import { api } from 'utils/api'
import {
Tokens,
Authentication as AuthenticationClass
} from '../../utils/authentication'
import { getErrorTranslationKey } from './getErrorTranslationKey'
interface Errors {
[key: string]: ErrorObject<string, any> | null | undefined
}
const findError = (
field: string
): ((value: ErrorObject, index: number, object: ErrorObject[]) => boolean) => {
return (validationError) => validationError.instancePath === field
}
import { useForm, HandleSubmitCallback } from '../../hooks/useForm'
export interface AuthenticationProps {
mode: 'signup' | 'signin'
@ -44,84 +28,57 @@ export const Authentication: React.FC<AuthenticationProps> = (props) => {
const router = useRouter()
const { lang, t } = useTranslation()
const { theme } = useTheme()
const [formState, setFormState] = useFormState()
const [messageTranslationKey, setMessageTranslationKey] = useState<
string | undefined
>(undefined)
const [errors, setErrors] = useState<Errors>({
name: null,
email: null,
password: null
})
const validateSchema = useMemo(() => {
return Type.Object({
...(mode === 'signup' && { name: userSchema.name }),
email: userSchema.email,
password: userSchema.password
const { errors, formState, message, getErrorTranslation, handleSubmit } =
useForm({
validateSchemaObject: {
...(mode === 'signup' && { name: userSchema.name }),
email: userSchema.email,
password: userSchema.password
}
})
}, [mode])
const validate = useMemo(() => {
return ajv.compile(validateSchema)
}, [validateSchema])
const getErrorTranslation = (error?: ErrorObject | null): string | null => {
if (error != null) {
return t(getErrorTranslationKey(error)).replace(
'{expected}',
error?.params?.limit
)
}
return null
}
const handleSubmit: HandleForm = async (formData, formElement) => {
const isValid = validate(formData)
if (!isValid) {
setFormState('error')
const nameError = validate?.errors?.find(findError('/name'))
const emailError = validate?.errors?.find(findError('/email'))
const passwordError = validate?.errors?.find(findError('/password'))
setErrors({
name: nameError,
email: emailError,
password: passwordError
})
} else {
setErrors({})
setFormState('loading')
if (mode === 'signup') {
try {
await api.post(
`/users/signup?redirectURI=${window.location.origin}/authentication/signin`,
{ ...formData, language: lang, theme }
)
formElement.reset()
setFormState('success')
setMessageTranslationKey('authentication:success-signup')
} catch (error) {
setFormState('error')
if (axios.isAxiosError(error) && error.response?.status === 400) {
setMessageTranslationKey('authentication:alreadyUsed')
} else {
setMessageTranslationKey('errors:server-error')
const onSubmit: HandleSubmitCallback = async (formData) => {
if (mode === 'signup') {
try {
await api.post(
`/users/signup?redirectURI=${window.location.origin}/authentication/signin`,
{ ...formData, language: lang, theme }
)
return {
type: 'success',
value: 'authentication:success-signup'
}
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 400) {
return {
type: 'error',
value: 'authentication:alreadyUsed'
}
}
} else {
try {
const { data } = await api.post<Tokens>('/users/signin', formData)
const authentication = new AuthenticationClass(data)
authentication.signin()
await router.push('/application')
} catch (error) {
setFormState('error')
if (axios.isAxiosError(error) && error.response?.status === 400) {
setMessageTranslationKey('authentication:wrong-credentials')
} else {
setMessageTranslationKey('errors:server-error')
return {
type: 'error',
value: 'errors:server-error'
}
}
} else {
try {
const { data } = await api.post<Tokens>('/users/signin', formData)
const authentication = new AuthenticationClass(data)
authentication.signin()
await router.push('/application')
return null
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 400) {
return {
type: 'error',
value: 'authentication:wrong-credentials'
}
}
return {
type: 'error',
value: 'errors:server-error'
}
}
}
}
@ -138,13 +95,13 @@ export const Authentication: React.FC<AuthenticationProps> = (props) => {
<section className='text-center text-lg font-paragraph pt-8'>
{t('authentication:or')}
</section>
<AuthenticationForm onSubmit={handleSubmit}>
<AuthenticationForm onSubmit={handleSubmit(onSubmit)}>
{mode === 'signup' && (
<Input
type='text'
placeholder={t('authentication:name')}
placeholder={t('common:name')}
name='name'
label={t('authentication:name')}
label={t('common:name')}
error={getErrorTranslation(errors.name)}
/>
)}
@ -182,13 +139,7 @@ export const Authentication: React.FC<AuthenticationProps> = (props) => {
</Link>
</p>
</AuthenticationForm>
<FormState
id='message'
state={formState}
message={
messageTranslationKey != null ? t(messageTranslationKey) : null
}
/>
<FormState id='message' state={formState} message={message} />
</Main>
)
}

View File

@ -1,71 +0,0 @@
import type { ErrorObject } from 'ajv'
import { getErrorTranslationKey } from './getErrorTranslationKey'
const errorObject: ErrorObject = {
instancePath: '/path',
keyword: 'keyword',
params: {},
schemaPath: '/path'
}
describe('Authentication/getErrorTranslationKey', () => {
it('returns `errors:invalid` with unknown keyword', async () => {
expect(
getErrorTranslationKey({
...errorObject,
keyword: 'unknownkeyword'
})
).toEqual('errors:invalid')
})
it('returns `errors:invalid` with format != email', () => {
expect(
getErrorTranslationKey({
...errorObject,
keyword: 'format',
params: { format: 'email' }
})
).toEqual('errors:email')
})
it('returns `errors:email` with format = email', () => {
expect(
getErrorTranslationKey({
...errorObject,
keyword: 'format',
params: { format: 'email' }
})
).toEqual('errors:email')
})
it('returns `errors:required` with minLength and limit = 1', () => {
expect(
getErrorTranslationKey({
...errorObject,
keyword: 'minLength',
params: { limit: 1 }
})
).toEqual('errors:required')
})
it('returns `errors:minLength` with minLength and limit > 1', () => {
expect(
getErrorTranslationKey({
...errorObject,
keyword: 'minLength',
params: { limit: 5 }
})
).toEqual('errors:minLength')
})
it('returns `errors:maxLength` with maxLength', () => {
expect(
getErrorTranslationKey({
...errorObject,
keyword: 'maxLength',
params: { limit: 5 }
})
).toEqual('errors:maxLength')
})
})

View File

@ -1,19 +0,0 @@
import type { ErrorObject } from 'ajv'
const knownErrorKeywords = ['minLength', 'maxLength', 'format']
export const getErrorTranslationKey = (error: ErrorObject): string => {
if (knownErrorKeywords.includes(error?.keyword)) {
if (error.keyword === 'minLength' && error.params.limit === 1) {
return 'errors:required'
}
if (error.keyword === 'format') {
if (error.params.format === 'email') {
return 'errors:email'
}
return 'errors:invalid'
}
return `errors:${error.keyword}`
}
return 'errors:invalid'
}