Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -209,4 +209,10 @@ sketch

# Support for Project snippet scope

# End of https://www.toptal.com/developers/gitignore/api/react,macos,nextjs,visualstudiocode,node
# End of https://www.toptal.com/developers/gitignore/api/react,macos,nextjs,visualstudiocode,node

# firebase
firebaseConfig.ts
.firebaserc
firebase.json
.firebase
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
"dependencies": {
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@types/yup": "^0.29.13",
"emotion-normalize": "^11.0.1",
"firebase": "^9.6.8",
"formik": "^2.2.9",
"next": "12.1.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-icons": "^4.3.1",
"react-loading-icons": "^1.0.8"
"react-loading-icons": "^1.0.8",
"yup": "^0.32.11"
},
"devDependencies": {
"@babel/core": "^7.17.7",
Expand Down
53 changes: 53 additions & 0 deletions src/api/requestAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { initializeApp } from 'firebase/app';
import { getFirestore, setDoc, doc, Timestamp } from 'firebase/firestore';
import {
getAuth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut,
onAuthStateChanged,
} from 'firebase/auth';
import { SignInFormValues, SignUpFormValues } from 'components/Auth/Auth.types';
import { firebaseConfig } from './firebaseConfig';

initializeApp(firebaseConfig);

const auth = getAuth();
const db = getFirestore();

export const getAuthStatus = async () => {
return new Promise((resolve, reject) => {
try {
onAuthStateChanged(auth, (user) => resolve(user));
} catch (e) {
reject(e);
}
});
};

export const signIn = async ({ email, password }: SignInFormValues) => {
try {
const { user } = await signInWithEmailAndPassword(auth, email, password);
return user;
} catch (error) {
throw new Error(error.code);
}
};

export const signUp = async ({ username, email, password }: SignUpFormValues) => {
try {
const { user } = await createUserWithEmailAndPassword(auth, email, password);
const docRef = await setDoc(doc(db, 'users', user.uid), {
username,
email,
createdAt: Timestamp.fromDate(new Date()),
});
return user;
} catch (error) {
throw new Error(error.code);
}
};

export const logOut = () => {
signOut(auth);
};
14 changes: 14 additions & 0 deletions src/components/Auth/Auth.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { Auth } from './Auth';

export default {
title: 'Auth',
component: Auth,
args: { currentForm: 'signin' },
} as ComponentMeta<typeof Auth>;

const Template: ComponentStory<typeof Auth> = (args) => <Auth {...args} />;

export const SignInForm = Template.bind({});
export const SignUpForm = Template.bind({});
SignUpForm.args = { currentForm: 'signup' };
19 changes: 19 additions & 0 deletions src/components/Auth/Auth.styled.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import styled from '@emotion/styled';
import { pxToRem } from 'utils';
import { StyleInputProps } from './Auth.types';

export const StyledFieldError = styled.div`
height: ${pxToRem(32)};
line-height: 1.8;
font-size: ${pxToRem(16)};
color: ${({ theme }) => theme.color.primaryOrange};
padding: 0 ${pxToRem(20)};
`;

export const StyledInput = styled.input<StyleInputProps>`
padding: 0 ${pxToRem(24)};
height: ${pxToRem(36)};
border: none;
border-radius: ${pxToRem(5)} ${pxToRem(5)};
${({ $warning, theme }) => $warning && `box-shadow: 0 0 1px 5px ${theme.color.primaryOrange};`}
`;
42 changes: 42 additions & 0 deletions src/components/Auth/Auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { FormikProps, withFormik } from 'formik';
import { FormValues, FormProps } from './Auth.types';
import { StyledInput, StyledFieldError } from './Auth.styled';
import { AUTH_FUNC, SCHEMA, INITIAL_VALUES, FIELDS, HEADING, PLACEHOLDER, TYPE } from './AuthServices';

const AuthForm = (props: FormProps & FormikProps<FormValues>): JSX.Element => {
const { currentForm, values, errors, dirty, touched, isValid, handleChange, handleBlur, handleSubmit } = props;
return (
<form onSubmit={handleSubmit}>
{FIELDS[currentForm].map((field): JSX.Element => (
<>
<label className="a11yHidden" htmlFor={field}>
{field.toUpperCase()}
</label>
<StyledInput
id={field}
$warning={touched[field] && errors[field]}
name={field}
placeholder={PLACEHOLDER[field]}
type={TYPE[field]}
onChange={handleChange}
onBlur={handleBlur}
value={values[field] || ''}
/>
<StyledFieldError>{touched[field] && errors[field]}</StyledFieldError>
</>
))}

<button type="submit" disabled={!dirty || !isValid}>
{HEADING[currentForm]}
</button>
</form>
);
};

export const Auth = withFormik<FormProps, FormValues>({
mapPropsToValues: ({ currentForm }) => INITIAL_VALUES[currentForm],
validationSchema: ({ currentForm }: FormProps) => SCHEMA[currentForm],
handleSubmit(values: FormValues, { props: { currentForm } }) {
AUTH_FUNC[currentForm](values);
},
})(AuthForm);
23 changes: 23 additions & 0 deletions src/components/Auth/Auth.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export interface SignInFormValues {
password: string;
email: string;
}

export interface SignUpFormValues extends SignInFormValues {
username: string;
passwordConfirm: string;
}

export type FormValues = SignInFormValues | SignUpFormValues;

export interface FormProps {
initialEmail?: string;
initialPassword?: string;
initialPasswordConfirm?: string;
initialUsername?: string;
currentForm: 'signin' | 'signup';
}

export interface StyleInputProps {
$warning: boolean;
}
69 changes: 69 additions & 0 deletions src/components/Auth/AuthServices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { signIn, signUp } from 'api/requestAuth';
import * as Yup from 'yup';

export const TOGGLE_MESSAGE = {
signin: 'Not registered yet? Sign up here!',
signup: 'Already a member? Sign in here!',
} as const;

export const HEADING = {
signin: 'Sign In',
signup: 'Sign Up',
} as const;

export const PLACEHOLDER = {
username: 'Username',
email: 'Email',
password: 'Password',
passwordConfirm: 'Confirm password',
} as const;

export const TYPE = {
username: 'text',
email: 'email',
password: 'password',
passwordConfirm: 'password',
} as const;

export const INITIAL_VALUES = {
signin: {
password: '',
email: '',
},
signup: {
username: '',
password: '',
passwordConfirm: '',
email: '',
},
} as const;

export const SCHEMA = {
signin: Yup.object({
password: Yup.string().min(8, 'Must be 8 characters or more').required('Required'),
email: Yup.string().email('Invalid email address').required('Required'),
}),
signup: Yup.object({
username: Yup.string().min(3, 'Must be 3 characters or more').required('Required'),
password: Yup.string().min(8, 'Must be 8 characters or more').required('Required'),
passwordConfirm: Yup.string()
.oneOf([Yup.ref('password'), null], 'Passwords must match')
.required('Required'),
email: Yup.string().email('Invalid email address').required('Required'),
}),
} as const;

export const AUTH_ERROR_MSG = {
signin: 'Sign in failed. Please try again.',
signup: 'Sign up failed. Please try again.',
} as const;

export const FIELDS = {
signin: ['email', 'password'],
signup: ['username', 'email', 'password', 'passwordConfirm'],
} as const;

export const AUTH_FUNC = {
signin: signIn,
signup: signUp,
} as const;
11 changes: 0 additions & 11 deletions src/components/EmptyPage/EmptyPage.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { ComponentMeta, ComponentStory } from '@storybook/react';
import Link from 'next/link';
import { ThemeProvider } from '@emotion/react';
import { theme } from 'theme/theme';
import { GlobalStyle } from 'styles/GlobalStyle';
import { EmptyPage } from './EmptyPage';

export default {
Expand All @@ -16,14 +13,6 @@ export default {
</>
),
},
decorators: [
(Story) => (
<ThemeProvider theme={theme}>
<GlobalStyle />
<Story />
</ThemeProvider>
),
],
} as ComponentMeta<typeof EmptyPage>;

const Template: ComponentStory<typeof EmptyPage> = (args) => <EmptyPage {...args} />;
Expand Down
11 changes: 0 additions & 11 deletions src/components/Pagination/Pagination.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { ThemeProvider } from '@emotion/react';
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { GlobalStyle } from 'styles/GlobalStyle';
import { theme } from 'theme/theme';
import { Pagination } from './Pagination';

export default {
Expand All @@ -13,14 +10,6 @@ export default {
totalResults: 100,
limit: 5,
},
decorators: [
(Story) => (
<ThemeProvider theme={theme}>
<GlobalStyle />
<Story />
</ThemeProvider>
),
],
} as ComponentMeta<typeof Pagination>;

const Template: ComponentStory<typeof Pagination> = (args) => <Pagination {...args} />;
Expand Down
34 changes: 28 additions & 6 deletions src/components/Pagination/Pagination.styled.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
export interface PaginationProps {
currentPage: number;
onClick: (currentPage: number) => void;
totalResults: number;
limit: number;
}
import styled from '@emotion/styled';
import { pxToRem } from 'utils';

export const StyledPaginationControl = styled.div`
display: flex;
justify-contents: center;
align-items: center;
gap: ${pxToRem(20)};
ul {
display: flex;
justify-contents: center;
align-items: center;
gap: ${pxToRem(10)};
}
`;

export const StyledPageButton = styled.button`
color: ${({ theme, current }) => (current ? theme.color.white : theme.color.primaryOrange)};
border: 1px solid ${({ theme }) => theme.color.primaryOrange};
border-radius: ${pxToRem(5)};
background-color: ${({ theme, current }) => (current ? theme.color.primaryOrange : theme.color.white)};
width: ${pxToRem(32)};
height: ${pxToRem(32)};
margin: ${pxToRem(6)};
&:hover {
opacity: 0.5;
}
`;
9 changes: 4 additions & 5 deletions src/components/Pagination/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { IoIosArrowBack, IoIosArrowForward } from 'react-icons/io';
import { PaginationProps } from './Pagination.styled';
import { StyledPageButton, StyledPaginationControl } from './Pagination.types';
import { usePageNum } from 'hooks/usePageNum';
import { PaginationProps } from './Pagination.types';
import { StyledPageButton, StyledPaginationControl } from './Pagination.styled';

export const Pagination = ({ limit, currentPage, onClick: handleClick, totalResults }: PaginationProps) => {
const lastPageNum = Math.ceil(totalResults / limit);
const pageStartNum = Math.max(currentPage - 2, 1);
const pageEndNum = Math.min(currentPage + 2, lastPageNum);
const { pageStartNum, pageEndNum } = usePageNum({ currentPage, totalResults, limit });
return (
<StyledPaginationControl>
<StyledPageButton
Expand Down
34 changes: 6 additions & 28 deletions src/components/Pagination/Pagination.types.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,6 @@
import styled from '@emotion/styled';
import { pxToRem } from '../../utils';

export const StyledPaginationControl = styled.div`
display: flex;
justify-contents: center;
align-items: center;
gap: ${pxToRem(20)};
ul {
display: flex;
justify-contents: center;
align-items: center;
gap: ${pxToRem(10)};
}
`;

export const StyledPageButton = styled.button`
color: ${({ theme, current }) => (current ? theme.color.white : theme.color.primaryOrange)};
border: 1px solid ${({ theme }) => theme.color.primaryOrange};
border-radius: ${pxToRem(5)};
background-color: ${({ theme, current }) => (current ? theme.color.primaryOrange : theme.color.white)};
width: ${pxToRem(32)};
height: ${pxToRem(32)};
margin: ${pxToRem(6)};
&:hover {
opacity: 0.5;
}
`;
export interface PaginationProps {
currentPage: number;
onClick: (currentPage: number) => void;
totalResults: number;
limit: number;
}
Loading