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

refactor: Dialog 레이어 쌓임 문제 해결 #96

Open
wants to merge 4 commits into
base: main
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
38 changes: 30 additions & 8 deletions src/BottomSheet/BottomSheet.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Meta, StoryObj } from '@storybook/react';

import BottomSheet from './BottomSheet';
import { useBottomSheet } from './useBottomSheet';

import BottomSheet from './BottomSheet';
import { useToastActionContext } from '../Toast/context/useToastActionContext';

const meta: Meta<typeof BottomSheet> = {
title: 'BottomSheet',
component: BottomSheet,
Expand All @@ -25,31 +27,31 @@ type Story = StoryObj<typeof BottomSheet>;

export const Default: Story = {
render: () => {
const { isOpen, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();
const { ref, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();

return (
<>
<button type="button" style={{ padding: '10px', border: '1px solid gray' }} onClick={handleOpenBottomSheet}>
바텀시트 열기
</button>
<BottomSheet isOpen={isOpen} isClosing={isClosing} close={handleCloseBottomSheet}>
<BottomSheet isClosing={isClosing} close={handleCloseBottomSheet} ref={ref}>
<div style={{ padding: '20px' }}>바텀시트 컴포넌트</div>
</BottomSheet>
</>
);
},
};

export const WithMaxWidth: Story = {
export const MaxWidth: Story = {
render: () => {
const { isOpen, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();
const { ref, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();

return (
<>
<button type="button" style={{ padding: '10px', border: '1px solid gray' }} onClick={handleOpenBottomSheet}>
바텀시트 열기
</button>
<BottomSheet isOpen={isOpen} isClosing={isClosing} maxWidth="300px" close={handleCloseBottomSheet}>
<BottomSheet isClosing={isClosing} maxWidth="300px" close={handleCloseBottomSheet} ref={ref}>
<div style={{ padding: '20px' }}>바텀시트 컴포넌트</div>
</BottomSheet>
</>
Expand All @@ -59,14 +61,14 @@ export const WithMaxWidth: Story = {

export const MaxHeight: Story = {
render: () => {
const { isOpen, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();
const { ref, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();

return (
<>
<button type="button" style={{ padding: '10px', border: '1px solid gray' }} onClick={handleOpenBottomSheet}>
바텀시트 열기
</button>
<BottomSheet isOpen={isOpen} isClosing={isClosing} close={handleCloseBottomSheet}>
<BottomSheet isClosing={isClosing} close={handleCloseBottomSheet} ref={ref}>
<div style={{ padding: '20px' }}>
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical
Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
Expand Down Expand Up @@ -144,3 +146,23 @@ export const MaxHeight: Story = {
);
},
};

export const WithToast: Story = {
render: () => {
const { ref, isClosing, handleOpenBottomSheet, handleCloseBottomSheet } = useBottomSheet();
const { toast } = useToastActionContext();

return (
<>
<button type="button" style={{ padding: '10px', border: '1px solid gray' }} onClick={handleOpenBottomSheet}>
바텀시트 열기
</button>
<BottomSheet hasToast isClosing={isClosing} close={handleCloseBottomSheet} ref={ref}>
<div style={{ padding: '20px' }}>
<button onClick={() => toast.success('토스트 테스트 중')}>토스트 버튼</button>
</div>
</BottomSheet>
</>
);
},
};
37 changes: 17 additions & 20 deletions src/BottomSheet/BottomSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,45 +5,42 @@ import styled from 'styled-components';

import { slideDown, slideUp } from '../styles/animations';

export interface BottomSheetProps extends ComponentPropsWithRef<'div'> {
maxWidth?: string;
isOpen: boolean;
export interface BottomSheetProps extends ComponentPropsWithRef<'dialog'> {
isClosing: boolean;
maxWidth?: string;
maxHeight?: string;
hasToast?: boolean;
close: () => void;
}

const containerElement =
window.location.port === '6006' ? document.body : (document.getElementById('dialog-container') as HTMLElement);

const BottomSheet = (
{ maxWidth, isOpen, isClosing, close, children, ...props }: BottomSheetProps,
ref: ForwardedRef<HTMLDivElement>
{ maxWidth, maxHeight, isClosing, close, hasToast, children, ...props }: BottomSheetProps,
ref: ForwardedRef<HTMLDialogElement>
) => {
return createPortal(
<>
{isOpen && (
<ModalDialog role="dialog" ref={ref} {...props}>
<BackDrop onClick={close} />
<ModalWrapper maxWidth={maxWidth} isClosing={isClosing}>
{children}
</ModalWrapper>
</ModalDialog>
)}
</>,
<ModalDialog ref={ref} {...props}>
<BackDrop onClick={close} />
<ModalWrapper maxWidth={maxWidth} isClosing={isClosing}>
{children}
</ModalWrapper>
{hasToast && <div id="toast-in-dialog-container" aria-hidden />}
</ModalDialog>,
containerElement
);
};

export default forwardRef(BottomSheet);

type ModalWrapperStyleProps = Pick<BottomSheetProps, 'maxWidth'> & {
type ModalWrapperStyleProps = Pick<BottomSheetProps, 'maxWidth' | 'maxHeight'> & {
isClosing: boolean;
};

const ModalDialog = styled.div`
position: relative;
const ModalDialog = styled.dialog`
border: none;
z-index: 9999;
z-index: 1000;
Copy link
Collaborator

Choose a reason for hiding this comment

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

펀잇 헤더가 1001이라 헤더가 위에 있지 싶네요..?
나중에 z-index도 상수화 얘기해보죠.!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

얘는 아마 z-index가 상관이 없을거에여!
제가 알기로는 dialog가 z-index 상관없이 무조건 최상위라고 알고있거든요?
그래서 저거 지울까하다가 일단 수만 줄여서 나뒀는데 저거 지울까여 아니면 9999로 다시 올릴까여??

`;

const BackDrop = styled.div`
Expand All @@ -64,7 +61,7 @@ const ModalWrapper = styled.div<ModalWrapperStyleProps>`
left: 0;
width: 100%;
max-width: ${({ maxWidth }) => maxWidth};
max-height: 100%;
max-height: ${({ maxHeight }) => maxHeight}
border-radius: 12px 12px 0px 0px;
background: ${({ theme }) => theme.colors.white};
overflow-y: auto;
Expand Down
30 changes: 10 additions & 20 deletions src/BottomSheet/useBottomSheet.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,32 @@
import type { KeyboardEventHandler } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useRef, useState } from 'react';
import { useToastActionContext } from '../Toast';

export const useBottomSheet = () => {
const [isOpen, setIsOpen] = useState(false);
const [isClosing, setIsClosing] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const ref = useRef<HTMLDialogElement>(null);

Copy link
Collaborator

Choose a reason for hiding this comment

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

오 dialog 태그로 바꿔서 ref로 핸들링하는거군요 👍

const { setToastId } = useToastActionContext();

const closeAnimated = useCallback(() => {
setIsClosing(true);

const timer = setTimeout(() => {
setIsClosing(false);
setIsOpen(false);
ref.current?.close();
}, 370);

return () => clearTimeout(timer);
}, []);

const handleOpenBottomSheet = () => {
setIsOpen(true);
setToastId('toast-in-dialog-container');
ref.current?.showModal();
};

const handleCloseBottomSheet = () => {
setToastId('toast-container');
closeAnimated();
};

const handleKeydown = (e: KeyboardEvent) => {
if (e.keyCode === 27) {
e.preventDefault();
handleCloseBottomSheet();
}
};

useEffect(() => {
document.addEventListener('keydown', handleKeydown);

return () => document.removeEventListener('keydown', handleKeydown);
}, [handleKeydown]);

return { ref, isOpen, isClosing, handleOpenBottomSheet, handleCloseBottomSheet };
return { ref, isClosing, handleOpenBottomSheet, handleCloseBottomSheet };
};
10 changes: 9 additions & 1 deletion src/Toast/context/ToastContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createPortal } from 'react-dom';
import styled from 'styled-components';

import Toast from '..';
import { ToastId } from '../../types';

export interface ToastState {
id: number;
Expand All @@ -21,13 +22,15 @@ export interface ToastAction {
error: (message: string) => void;
};
deleteToast: (id: number) => void;
setToastId: (id: ToastId) => 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 [toastElementId, setToastElementId] = useState<ToastId>('toast-container');

const showToast = (id: number, message: string, isError?: boolean) => {
setToasts([...toasts, { id, message, isError }]);
Expand All @@ -37,6 +40,10 @@ export const ToastProvider = ({ children }: PropsWithChildren) => {
setToasts((prevToasts) => prevToasts.filter((toast) => toast.id !== id));
};

const setToastId = (id: ToastId) => {
setToastElementId(id);
};

const toast = {
success: (message: string) => showToast(Number(Date.now()), message),
error: (message: string) => showToast(Number(Date.now()), message, true),
Expand All @@ -49,6 +56,7 @@ export const ToastProvider = ({ children }: PropsWithChildren) => {
const toastAction = {
toast,
deleteToast,
setToastId,
};

return (
Expand All @@ -61,7 +69,7 @@ export const ToastProvider = ({ children }: PropsWithChildren) => {
<Toast key={id} id={id} message={message} isError={isError} />
))}
</ToastContainer>,
document.getElementById('toast-container') as HTMLElement
document.getElementById(toastElementId) as HTMLElement
)}
</ToastValueContext.Provider>
</ToastActionContext.Provider>
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ export type OverridableComponentPropsWithRef<T extends ElementType, P = unknown>
ComponentPropsWithRef<T> & { as?: T };
export type OverridableComponentPropsWithoutRef<T extends ElementType, P = unknown> = P &
ComponentPropsWithoutRef<T> & { as?: T };

export type ToastId = 'toast-container' | 'toast-in-dialog-container';
Loading