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: 토스트 컴포넌트 마이그레이션 #170

Open
wants to merge 4 commits into
base: feat/v2
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .storybook/preview-body.html
Original file line number Diff line number Diff line change
Expand Up @@ -409,4 +409,5 @@
</svg>
</div>
<div id="dialog-container"></div>
<div id="toast-container-root"></div>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요거 밑에 있는 toast-container 안 쓰고 새로 만든 이유가 뭐예요?!

<div id="toast-container"></div>
5 changes: 4 additions & 1 deletion .storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from '../src/mocks/handlers';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import ToastProvider from '../src/components/Common/Toast/context/ToastContext';

initialize({
serviceWorker: {
Expand All @@ -27,7 +28,9 @@ export const decorators = [
<QueryClientProvider client={queryClient}>
<FunEatProvider>
<BrowserRouter>
<Story />
<ToastProvider>
<Story />
</ToastProvider>
</BrowserRouter>
</FunEatProvider>
</QueryClientProvider>
Expand Down
1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
/>
</head>
<body>
<div id="toast-container-root"></div>
<div id="root"></div>
<div id="dialog-container"></div>
<div id="toast-container"></div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Common/ImageUploader/ImageUploader.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useToastActionContext } from '@fun-eat/design-system';
import type { ChangeEventHandler } from 'react';

import { container, deleteButton, image, imageWrapper, uploadInput, uploadLabel } from './imageUploader.css';
import SvgIcon from '../Svg/SvgIcon';
import { useToastActionContext } from '../Toast/context';
import Text from '../Typography/Text/Text';

import { IMAGE_MAX_SIZE } from '@/constants';
Expand Down
48 changes: 48 additions & 0 deletions src/components/Common/Toast/Toast.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { Meta, StoryObj } from '@storybook/react';

import { useToastActionContext } from './context';
import ToastProvider from './context/ToastContext';
import Toast from './Toast';

const meta: Meta<typeof Toast> = {
title: 'common/Toast',
component: Toast,
decorators: [
(Story) => (
<ToastProvider>
<Story />
</ToastProvider>
),
],
};

export default meta;
type Story = StoryObj<typeof Toast>;

export const Default: Story = {
render: () => {
const { toast } = useToastActionContext();
const handleClick = () => {
toast.success('성공');
};
return (
<div style={{ width: '375px' }}>
<button onClick={handleClick}>토스트 성공</button>
</div>
);
},
};

export const Error: Story = {
render: () => {
const { toast } = useToastActionContext();
const handleClick = () => {
toast.error('실패');
};
return (
<div style={{ width: '375px' }}>
<button onClick={handleClick}>토스트 에러</button>
</div>
);
},
};
25 changes: 25 additions & 0 deletions src/components/Common/Toast/Toast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import cx from 'classnames';

import { wrapper, toastMessage } from './toast.css';
import useToast from './useToast';
import Text from '../Typography/Text/Text';

export interface ToastProps {
id: number;
message: string;
isError?: boolean;
}

const Toast = ({ id, message, isError = false }: ToastProps) => {
const isShown = useToast(id);

return (
<div className={cx(wrapper, { isError, isShown })}>
<Text color="white" aria-live="assertive" className={toastMessage}>
{message}
</Text>
</div>
);
};

export default Toast;
71 changes: 71 additions & 0 deletions src/components/Common/Toast/context/ToastContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import type { PropsWithChildren } from 'react';
import { createContext, useState } from 'react';
import { createPortal } from 'react-dom';

import Toast from '../Toast';
import { container } from '../toast.css';

export interface ToastState {
id: number;
message: string;
isError?: boolean;
}

export interface ToastValue {
toasts: ToastState[];
}

export interface ToastAction {
toast: {
success: (message: string) => void;
error: (message: string) => void;
};
deleteToast: (id: number) => void;
}

export const ToastValueContext = createContext<ToastValue | null>(null);
export const ToastActionContext = createContext<ToastAction | null>(null);

export const ToastProvider = ({ children }: PropsWithChildren) => {
const [toasts, setToasts] = useState<ToastState[]>([]);

const showToast = (id: number, message: string, isError?: boolean) => {
setToasts([...toasts, { id, message, isError }]);
};

const deleteToast = (id: number) => {
setToasts((prevToasts) => prevToasts.filter((toast) => toast.id !== id));
};

const toast = {
success: (message: string) => showToast(Number(Date.now()), message),
error: (message: string) => showToast(Number(Date.now()), message, true),
};

const toastValue = {
toasts,
};

const toastAction = {
toast,
deleteToast,
};

return (
<ToastActionContext.Provider value={toastAction}>
<ToastValueContext.Provider value={toastValue}>
{children}
{createPortal(
<div className={container}>
{toasts.map(({ id, message, isError }) => (
<Toast key={id} id={id} message={message} isError={isError} />
))}
</div>,
document.getElementById('toast-container-root') as HTMLElement
)}
</ToastValueContext.Provider>
</ToastActionContext.Provider>
);
};

export default ToastProvider;
3 changes: 3 additions & 0 deletions src/components/Common/Toast/context/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { default as useToastActionContext } from './useToastActionContext';
export { default as useToastValueContext } from './useToastValueContext';
export { default as ToastContext } from './ToastContext';
14 changes: 14 additions & 0 deletions src/components/Common/Toast/context/useToastActionContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useContext } from 'react';

import { ToastActionContext } from './ToastContext';

export const useToastActionContext = () => {
const toastAction = useContext(ToastActionContext);
if (!toastAction) {
throw new Error('useToastActionContext는 Toast Provider 안에서 사용해야 합니다.');
}

return toastAction;
};

export default useToastActionContext;
14 changes: 14 additions & 0 deletions src/components/Common/Toast/context/useToastValueContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useContext } from 'react';

import { ToastValueContext } from './ToastContext';

export const useToastValueContext = () => {
const toastValue = useContext(ToastValueContext);
if (!toastValue) {
throw new Error('useToastValueContext는 Toast Provider 안에서 사용해야 합니다.');
}

return toastValue;
};

export default useToastValueContext;
62 changes: 62 additions & 0 deletions src/components/Common/Toast/toast.css.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { vars } from '@/styles/theme.css';
import { keyframes, style } from '@vanilla-extract/css';

const fadeOut = keyframes({
'0%': {
transform: 'translateY(70px)',
opacity: 1,
},
'100%': {
transform: 'translateY(70px)',
opacity: 0,
},
});

const slideIn = keyframes({
'0%': {
transform: 'translateY(-100px)',
},
'100%': {
transform: 'translateY(70px)',
},
});

export const container = style({
position: 'fixed',
zIndex: 1000,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
width: '100%',
transform: 'translate(0, -10px)',
});

export const wrapper = style({
display: 'flex',
alignItems: 'center',
position: 'relative',
width: 'calc(100% - 20px)',
height: 55,
maxWidth: 560,
borderRadius: 10,
background: vars.colors.black,
selectors: {
'&.isError': {
backgroundColor: vars.colors.error,
},
'&.isShown': {
animation: `${slideIn} 0.3s ease-in-out forwards`,
},
'&:not(.isShown)': {
animation: `${fadeOut} 0.3s ease-in-out forwards`,
},
},
});

export const isError = style({
background: vars.colors.error,
});

export const toastMessage = style({
marginLeft: 20,
});
37 changes: 37 additions & 0 deletions src/components/Common/Toast/useToast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useEffect, useRef, useState } from 'react';

import { useToastActionContext } from './context';

const useToast = (id: number) => {
const { deleteToast } = useToastActionContext();
const [isShown, setIsShown] = useState(true);

const showTimeoutRef = useRef<number | null>(null);
const deleteTimeoutRef = useRef<number | null>(null);

useEffect(() => {
showTimeoutRef.current = window.setTimeout(() => setIsShown(false), 2000);

return () => {
if (showTimeoutRef.current) {
clearTimeout(showTimeoutRef.current);
}
};
}, []);

useEffect(() => {
if (!isShown) {
deleteTimeoutRef.current = window.setTimeout(() => deleteToast(id), 2000);
}

return () => {
if (deleteTimeoutRef.current) {
clearTimeout(deleteTimeoutRef.current);
}
};
}, [isShown]);

return isShown;
};

export default useToast;
4 changes: 2 additions & 2 deletions src/components/Members/MemberReviewItem/MemberReviewItem.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useToastActionContext } from '@fun-eat/design-system';
import type { MouseEventHandler } from 'react';
import { Link } from 'react-router-dom';

import { titleWrapper } from './memberReviewItem.css';

import { SvgIcon, Text } from '@/components/Common';
import { useToastActionContext } from '@/components/Common/Toast/context';
import { ReviewItemInfo } from '@/components/Review';
import { PATH } from '@/constants/path';
import { useDeleteReview } from '@/hooks/queries/members';
Expand Down Expand Up @@ -40,7 +40,7 @@ const MemberReviewItem = ({ review }: MemberReviewItemProps) => {
return;
}

toast.error('리뷰 좋아요를 다시 시도해주세요.');
toast.error('리뷰 삭제를 다시 시도해주세요.');
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍👍👍

});
};
Expand Down
2 changes: 1 addition & 1 deletion src/components/Recipe/CommentForm/CommentForm.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useToastActionContext } from '@fun-eat/design-system';
import type { ChangeEventHandler, FormEventHandler, RefObject } from 'react';
import { useRef, useState } from 'react';

import { commentForm, commentTextarea, container, sendButton } from './commentForm.css';

import { SvgIcon, Text } from '@/components/Common';
import { useToastActionContext } from '@/components/Common/Toast/context';
import { MemberImage } from '@/components/Members';
import { useScroll } from '@/hooks/common';
import { useMemberQuery } from '@/hooks/queries/members';
Expand Down
Loading
Loading