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
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Button from '@/shared/components/button/Button';
import { Button } from '@/shared/components/Button';
import { Icon } from '@/shared/components/icon/Icon';
import Input from '@/shared/components/Input';
import { Input } from '@/shared/components/Input';
import type { PollOption } from '../types';

interface PollOptionItemProps {
Expand Down
25 changes: 4 additions & 21 deletions apps/frontend/src/shared/components/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,7 @@ import { MouseEvent, useEffect, type ReactNode } from 'react';
import { createPortal } from 'react-dom';

import { cn } from '@/shared/lib/utils';

/**
* ESC 키로 모달 닫기 기능을 제공하는 커스텀 훅
* @param isOpen 모달 열림 상태
* @param onClose 모달 닫기 함수
*/
function useModalEscapeClose(isOpen: boolean, onClose: () => void) {
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) onClose();
};

if (isOpen) {
document.addEventListener('keydown', handleEscape);
return () => document.removeEventListener('keydown', handleEscape);
}
}, [isOpen, onClose]);
}
import { useEscapeKey } from '@/shared/hooks/useEscapeKey';

/**
* 모달 열림 시 body 스크롤 방지 기능을 제공하는 커스텀 훅
Expand Down Expand Up @@ -81,8 +64,8 @@ interface ModalProps {
* @param className 추가 클래스 이름
* @returns 모달 JSX 요소
*/
export function Modal({ isOpen, onClose, children, className }: ModalProps) {
useModalEscapeClose(isOpen, onClose);
export const Modal = ({ isOpen, onClose, children, className }: ModalProps) => {
useEscapeKey(isOpen, onClose);
useModalBodyScrollLock(isOpen);

if (!isOpen) return null;
Expand All @@ -99,4 +82,4 @@ export function Modal({ isOpen, onClose, children, className }: ModalProps) {
</section>
</ModalOverlay>
);
}
};
134 changes: 134 additions & 0 deletions apps/frontend/src/shared/components/TimeLimitDropdown.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { TimeLimitDropdown } from './TimeLimitDropdown';

describe('TimeLimitDropdown', () => {
it('기본 상태에서 "제한 없음"이 표시된다', () => {
const handleChange = vi.fn();
render(<TimeLimitDropdown onChange={handleChange} />);

expect(screen.getByText('제한 없음')).toBeInTheDocument();
});

it('selectedTime prop에 따라 선택된 옵션이 표시된다', () => {
const handleChange = vi.fn();
render(
<TimeLimitDropdown
onChange={handleChange}
selectedTime={60}
/>,
);

expect(screen.getByText('1분')).toBeInTheDocument();
});

it('드롭다운 버튼을 클릭하면 옵션 리스트가 열린다', async () => {
const handleChange = vi.fn();
const user = userEvent.setup();

render(<TimeLimitDropdown onChange={handleChange} />);

const button = screen.getByRole('button');
await user.click(button);

expect(screen.getByRole('listbox')).toBeInTheDocument();
expect(screen.getByText('30초')).toBeInTheDocument();
expect(screen.getByText('3분')).toBeInTheDocument();
expect(screen.getByText('5분')).toBeInTheDocument();
expect(screen.getByText('10분')).toBeInTheDocument();
});

it('옵션을 클릭하면 onChange가 호출되고 드롭다운이 닫힌다', async () => {
const handleChange = vi.fn();
const user = userEvent.setup();

render(<TimeLimitDropdown onChange={handleChange} />);

const button = screen.getByRole('button');
await user.click(button);

const option = screen.getByText('1분');
await user.click(option);

expect(handleChange).toHaveBeenCalledWith(60);
expect(handleChange).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('열린 드롭다운을 다시 클릭하면 닫힌다', async () => {
const handleChange = vi.fn();
const user = userEvent.setup();

render(<TimeLimitDropdown onChange={handleChange} />);

const button = screen.getByRole('button');
await user.click(button);

expect(screen.getByRole('listbox')).toBeInTheDocument();

await user.click(button);

expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('선택된 옵션에 aria-selected가 적용된다', async () => {
const handleChange = vi.fn();
const user = userEvent.setup();

render(
<TimeLimitDropdown
onChange={handleChange}
selectedTime={60}
/>,
);

const button = screen.getByRole('button');
await user.click(button);

const selectedOption = screen.getByRole('option', { name: '1분' });
expect(selectedOption).toHaveAttribute('aria-selected', 'true');
});

it('모든 시간 제한 옵션이 정확하게 표시된다', async () => {
const handleChange = vi.fn();
const user = userEvent.setup();

render(<TimeLimitDropdown onChange={handleChange} />);

const button = screen.getByRole('button');
await user.click(button);

const listbox = screen.getByRole('listbox');
expect(listbox).toBeInTheDocument();

expect(screen.getByRole('option', { name: '제한 없음' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: '30초' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: '1분' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: '3분' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: '5분' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: '10분' })).toBeInTheDocument();
});

it('각 옵션 클릭 시 올바른 값이 전달된다', async () => {
const handleChange = vi.fn();
const user = userEvent.setup();

render(<TimeLimitDropdown onChange={handleChange} />);

const button = screen.getByRole('button');
await user.click(button);

await user.click(screen.getByText('30초'));
expect(handleChange).toHaveBeenCalledWith(30);

await user.click(button);
await user.click(screen.getByText('3분'));
expect(handleChange).toHaveBeenCalledWith(180);

await user.click(button);
await user.click(screen.getByText('10분'));
expect(handleChange).toHaveBeenCalledWith(600);
});
});
162 changes: 162 additions & 0 deletions apps/frontend/src/shared/components/TimeLimitDropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { useState, useRef } from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/shared/lib/utils';
import { Icon } from '@/shared/components/icon/Icon';
import { useEscapeKey } from '@/shared/hooks/useEscapeKey';
import { useOutsideClick } from '@/shared/hooks/useOutsideClick';

/**
* 시간 제한 옵션 배열
*/
const TIME_LIMIT_OPTIONS = [
{ label: '제한 없음', value: 0 },
{ label: '30초', value: 30 },
{ label: '1분', value: 60 },
{ label: '3분', value: 180 },
{ label: '5분', value: 300 },
{ label: '10분', value: 600 },
] as const;

/**
* 기본 시간 제한 값 (초 단위)
*/
const DEFAULT_TIME_LIMIT = 0;

/**
* 드롭다운 버튼 스타일 변형
*/
const dropdownButtonVariants = cva(
'text-text flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg bg-gray-300 px-4 py-2 text-sm transition-all duration-200 hover:bg-gray-200 focus-visible:ring-2',
{
variants: {
isOpen: {
true: 'bg-gray-300',
false: '',
},
},
defaultVariants: {
isOpen: false,
},
},
);

/**
* 드롭다운 아이템 스타일 변형
*/
const dropdownItemVariants = cva(
'text-text w-full cursor-pointer px-4 py-2 text-left text-sm transition-all duration-150 hover:bg-gray-300 active:bg-gray-200',
{
variants: {
isSelected: {
true: 'text-primary bg-gray-300 font-bold',
false: '',
},
},
defaultVariants: {
isSelected: false,
},
},
);

interface TimeLimitDropdownListProps {
selectedTime: number;
handleSelectTime: (time: number) => void;
}

/**
* 시간 제한 드롭다운 리스트 컴포넌트
* @param selectedTime 현재 선택된 시간 제한 값
* @param handleSelectTime 시간 제한 선택 핸들러
* @returns 시간 제한 드롭다운 리스트 JSX 요소
*/

function TimeLimitDropdownList({ selectedTime, handleSelectTime }: TimeLimitDropdownListProps) {
return (
<ul
role="listbox"
className="mt-1 overflow-y-auto rounded-lg bg-gray-400 shadow-lg"
>
{TIME_LIMIT_OPTIONS.map((option) => {
const isSelected = option.value === selectedTime;
return (
<li
key={option.value}
role="option"
aria-selected={isSelected}
onClick={() => handleSelectTime(option.value)}
className={dropdownItemVariants({ isSelected })}
>
{option.label}
</li>
);
})}
</ul>
);
}

interface TimeLimitDropdownProps extends VariantProps<typeof dropdownButtonVariants> {
onChange: (time: number) => void;
selectedTime?: number;
className?: string;
}

/**
* 시간 제한 드롭다운 컴포넌트
* @param className 추가 클래스 이름
* @param onChange 시간 제한 변경 핸들러
* @param selectedTime 현재 선택된 시간 제한 값
* @returns 시간 제한 드롭다운 JSX 요소
*/
export function TimeLimitDropdown({
onChange,
className,
selectedTime = DEFAULT_TIME_LIMIT,
}: TimeLimitDropdownProps) {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);

const selectedOption = TIME_LIMIT_OPTIONS.find((option) => option.value === selectedTime);
const displayLabel = selectedOption?.label ?? '시간 선택';

useOutsideClick(dropdownRef, isOpen, () => setIsOpen(false));
useEscapeKey(isOpen, () => setIsOpen(false));

const handleToggle = () => {
setIsOpen((prev) => !prev);
};

const handleSelect = (optionValue: number) => {
onChange(optionValue);
setIsOpen(false);
};

return (
<div
ref={dropdownRef}
className={cn('relative', className)}
>
<button
type="button"
onClick={handleToggle}
className={cn(dropdownButtonVariants({ isOpen }))}
aria-haspopup="listbox"
aria-expanded={isOpen}
>
<span className="text-sm font-bold">{displayLabel}</span>
<Icon
name="chevron"
size={24}
decorative
className={cn('transition-transform duration-200', isOpen && 'rotate-180')}
/>
</button>

{isOpen && (
<TimeLimitDropdownList
selectedTime={selectedTime}
handleSelectTime={handleSelect}
/>
Comment on lines +155 to +158
Copy link
Collaborator

@YunDo-Gi YunDo-Gi Jan 12, 2026

Choose a reason for hiding this comment

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

현재 구조는 부모 컨테이너 내부에 속해 있어서 드롭다운이 열릴 때 컨테이너의 전체 높이가 늘어나며 불필요한 스크롤이 생길 수도 있을 것 같아요. Portal 같은걸 사용해서 컨테이너에서 분리하면 좋지 않을까 생각해요!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

페이지 디자인 상에서 제한 시간 선택 의 위치를 고민하면서, 현재 컴포넌트 구조상 모달의 가장 하단에 위치해 있다는 점을 고려했습니다. 드롭다운을 모달 컨텐츠 외부로 띄우는 방식도 고려하면서 다음과 같은 결론을 내렸습니다.


드롭다운을 모달 컨텐츠 내부에 보여주기

모달 컨텐츠 영역 안에서만 드롭다운을 펼치면 뷰포트 안에서 모든 내용이 보장되어, 작은 화면에서도 동작이 더 안정적이라고 판단했습니다.

대신, 모달 컨텐츠 내부에서 스크롤을 해야하는 문제가 있었습니다.


드롭다운을 모달 컨텐츠 외부에 보여주기

드롭다운을 모달 컨텐츠 밖으로 띄우는 경우, 해상도가 작은 디스플레이에서는 모달 하단이 잘려서 옵션 일부가 보이지 않는 문제가 있었습니다.

스크린샷 2026-01-12 오후 12 55 07

이를 해결하기 위해서는 다음과 같이 스크롤을 해야만 했습니다.

스크린샷 2026-01-12 오후 12 59 47

이때는 모달 컨텐츠의 윗부분이 가려질 수도 있습니다.


정리하자면

결론은, 모달 컨텐츠를 한 페이지처럼 스크롤 없이 온전히 보여줄거냐 vs 드롭다운을 모달 컨텐츠 외부로 띄울 것니냐 의 결정해야했습니다.

저는 모달은 한 화면 안에서 스크롤 없이 모든 내용을 보여주는 것이 좋다고 생각하여, 전자를 선택하였습니다. 만약 후자가 나을 것 같다면 말씀해주시면 수정해두겠습니다!

Copy link
Collaborator

Choose a reason for hiding this comment

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

image

이런 식으로 유연하게 다른 방향으로 열리는걸 생각하기는 했는데, 결국 사용성 차이인 것 같아서 지금 상태로 진행해도 괜찮을 것 같아요!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

오 그렇다면 우선은 진행해두고, 해당 방안 조금 더 고민해보겠습니다!!!!

뭔가 useLayoutEffect 사용하면 잘 할 수 있을 것 같은데, 조금 알아봐야할 것 같아요. 다른 작업부터 마무리 짓겠습니다!

)}
</div>
);
}
23 changes: 23 additions & 0 deletions apps/frontend/src/shared/hooks/useEscapeKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useEffect } from 'react';

/**
* ESC 키 이벤트를 감지하여 콜백 함수를 실행하는 커스텀 훅
* @param isActive 훅 활성화 상태 (true일 때만 ESC 키 감지)
* @param onEscape ESC 키 입력 시 실행할 콜백 함수
*/
export function useEscapeKey(isActive: boolean, onEscape: () => void) {
useEffect(() => {
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onEscape();
}
};

if (isActive) {
document.addEventListener('keydown', handleEscape);
return () => {
document.removeEventListener('keydown', handleEscape);
};
}
}, [isActive, onEscape]);
}
Loading
Loading