-
Notifications
You must be signed in to change notification settings - Fork 0
feat: 제한 시간 드롭다운 구현 #67
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f2a0547
feat: ESC 키로 모달 닫기 기능을 제공하는 커스텀 훅 구현
KimDongGyun23 7fbabea
feat: 특정 요소 외부 클릭을 감지하는 커스텀 훅 구현
KimDongGyun23 71205d6
feat: 시간 제한 옵션 및 기본 값 상수 추가
KimDongGyun23 ecb09e6
feat: 시간 제한 드롭다운 컴포넌트 및 섹션 추가
KimDongGyun23 3f9d7aa
feat: 시간 제한 드롭다운 컴포넌트를 공통 컴포넌트로 분리
KimDongGyun23 577a5a6
feat: TimeLimitDropdown 컴포넌트에 대한 테스트 추가
KimDongGyun23 ce6763b
Merge branch 'develop' into feat/#60-poll-time
KimDongGyun23 902289b
fix: TimeLimitDropdownList 컴포넌트를 화살표 함수에서 일반 함수로 변경
KimDongGyun23 e6db301
fix: 드롭다운 리스트의 클래스에서 불필요한 위치 속성 제거
KimDongGyun23 b8a5645
fix: Button 및 Input 컴포넌트의 import 방식을 수정
KimDongGyun23 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
4 changes: 2 additions & 2 deletions
4
apps/frontend/src/feature/create-poll/components/PollOptionListSection.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
apps/frontend/src/shared/components/TimeLimitDropdown.spec.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
162
apps/frontend/src/shared/components/TimeLimitDropdown.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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} | ||
| /> | ||
| )} | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
현재 구조는 부모 컨테이너 내부에 속해 있어서 드롭다운이 열릴 때 컨테이너의 전체 높이가 늘어나며 불필요한 스크롤이 생길 수도 있을 것 같아요.
Portal같은걸 사용해서 컨테이너에서 분리하면 좋지 않을까 생각해요!There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
페이지 디자인 상에서
제한 시간 선택의 위치를 고민하면서, 현재 컴포넌트 구조상 모달의 가장 하단에 위치해 있다는 점을 고려했습니다. 드롭다운을 모달 컨텐츠 외부로 띄우는 방식도 고려하면서 다음과 같은 결론을 내렸습니다.모달 컨텐츠 영역 안에서만 드롭다운을 펼치면 뷰포트 안에서 모든 내용이 보장되어, 작은 화면에서도 동작이 더 안정적이라고 판단했습니다.
대신, 모달 컨텐츠 내부에서 스크롤을 해야하는 문제가 있었습니다.
드롭다운을 모달 컨텐츠 밖으로 띄우는 경우, 해상도가 작은 디스플레이에서는 모달 하단이 잘려서 옵션 일부가 보이지 않는 문제가 있었습니다.
이를 해결하기 위해서는 다음과 같이 스크롤을 해야만 했습니다.
이때는 모달 컨텐츠의 윗부분이 가려질 수도 있습니다.
결론은,
모달 컨텐츠를 한 페이지처럼 스크롤 없이 온전히 보여줄거냐vs드롭다운을 모달 컨텐츠 외부로 띄울 것니냐의 결정해야했습니다.저는 모달은 한 화면 안에서 스크롤 없이 모든 내용을 보여주는 것이 좋다고 생각하여, 전자를 선택하였습니다. 만약 후자가 나을 것 같다면 말씀해주시면 수정해두겠습니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이런 식으로 유연하게 다른 방향으로 열리는걸 생각하기는 했는데, 결국 사용성 차이인 것 같아서 지금 상태로 진행해도 괜찮을 것 같아요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오 그렇다면 우선은 진행해두고, 해당 방안 조금 더 고민해보겠습니다!!!!
뭔가 useLayoutEffect 사용하면 잘 할 수 있을 것 같은데, 조금 알아봐야할 것 같아요. 다른 작업부터 마무리 짓겠습니다!