-
Notifications
You must be signed in to change notification settings - Fork 4
feat(ui): DatePicker #323
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
Open
seong-hui
wants to merge
5
commits into
main
Choose a base branch
from
feat/#270-datepicker
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat(ui): DatePicker #323
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b47c695
feat(ui): Datepicker 컴포넌트 타입 및 상수 정의
seong-hui f8d6cd4
feat(ui): Datepicker Context 및 상태 관리 구현
seong-hui b78cc7b
feat(ui): Datepicker UI 컴포넌트 구현
seong-hui 79d982d
feat(ui): Datepicker 스타일 구현
seong-hui b761b3a
feat(ui): Datepicker 메인 컴포넌트 및 Public API 정의
seong-hui 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
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,201 @@ | ||
| import { useState, useEffect } from 'react'; | ||
| import type { Meta, StoryObj } from '@storybook/react'; | ||
| import { fn } from '@storybook/test'; | ||
| import { Datepicker, type DatepickerProps } from '@sopt-makers/ui'; | ||
|
|
||
| const meta = { | ||
| title: 'Components/DatePicker', | ||
| component: Datepicker, | ||
| tags: ['autodocs'], | ||
| parameters: { | ||
| layout: 'centered', | ||
| backgrounds: { | ||
| default: 'light', | ||
| values: [ | ||
| { name: 'light', value: '#ffffff' }, | ||
| { name: 'dark', value: '#1a1a1a' }, | ||
| ], | ||
| }, | ||
| }, | ||
| argTypes: { | ||
| disabled: { | ||
| control: 'boolean', | ||
| description: '컴포넌트를 비활성화합니다.', | ||
| }, | ||
| className: { | ||
| control: 'text', | ||
| description: '컴포넌트에 적용할 커스텀 className입니다.', | ||
| }, | ||
| }, | ||
| } satisfies Meta<typeof Datepicker>; | ||
|
|
||
| export default meta; | ||
| type Story = StoryObj<typeof meta>; | ||
|
|
||
| // Storybook의 date control은 timestamp를 반환하므로 Date 객체로 변환하는 헬퍼 함수 | ||
| const toDateOrNull = (value: Date | null | undefined | number): Date | null => { | ||
| if (!value) return null; | ||
| if (value instanceof Date) return value; | ||
| if (typeof value === 'number') return new Date(value); | ||
| return null; | ||
| }; | ||
|
|
||
| /** | ||
| * 단일 날짜 선택 | ||
| */ | ||
| const SingleDateExample = (args: DatepickerProps): JSX.Element => { | ||
| const [value, setValue] = useState<Date | null>(!args.isRange && 'value' in args ? toDateOrNull(args.value) : null); | ||
|
|
||
| useEffect(() => { | ||
| if (!args.isRange && 'value' in args) { | ||
| setValue(toDateOrNull(args.value)); | ||
| } | ||
| }, [args]); | ||
|
|
||
| const handleChange = (date: Date | null) => { | ||
| setValue(date); | ||
| if (!args.isRange && 'onChange' in args) { | ||
| args.onChange?.(date); | ||
| } | ||
| }; | ||
|
|
||
| return ( | ||
| <Datepicker | ||
| value={value} | ||
| onChange={handleChange} | ||
| disabled={args.disabled} | ||
| className={args.className} | ||
| placeholder={!args.isRange && 'placeholder' in args ? args.placeholder : undefined} | ||
| /> | ||
| ); | ||
| }; | ||
|
|
||
| /** | ||
| * 기본 Datepicker | ||
| * | ||
| * 단일 날짜를 선택할 수 있는 기본 Datepicker입니다. | ||
| * - Day 뷰와 Month 뷰를 전환할 수 있습니다. | ||
| * - 입력 필드에 직접 날짜를 입력할 수 있습니다. (YYYY.MM.DD 형식) | ||
| */ | ||
| export const Default: Story = { | ||
| render: (args) => <SingleDateExample {...args} />, | ||
| args: { | ||
| disabled: false, | ||
| placeholder: 'YYYY.MM.DD', | ||
| onChange: fn(), | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * 기본 값이 있는 Datepicker | ||
| * | ||
| * 초기 값을 설정한 Datepicker입니다. | ||
| */ | ||
| export const WithDefaultValue: Story = { | ||
| render: (args) => <SingleDateExample {...args} />, | ||
| args: { | ||
| disabled: false, | ||
| value: new Date(2000, 3, 29), | ||
| onChange: fn(), | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * 비활성화 상태 | ||
| * | ||
| * 비활성화된 Datepicker입니다. | ||
| */ | ||
| export const Disabled: Story = { | ||
| render: (args) => <SingleDateExample {...args} />, | ||
| args: { | ||
| disabled: true, | ||
| value: new Date(2025, 0, 1), | ||
| onChange: fn(), | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * 날짜 범위 선택 | ||
| */ | ||
| const DateRangeExample = (args: DatepickerProps) => { | ||
| const [startDate, setStartDate] = useState<Date | null>('startDate' in args ? toDateOrNull(args.startDate) : null); | ||
| const [endDate, setEndDate] = useState<Date | null>('endDate' in args ? toDateOrNull(args.endDate) : null); | ||
|
|
||
| useEffect(() => { | ||
| if ('startDate' in args) setStartDate(toDateOrNull(args.startDate)); | ||
| if ('endDate' in args) setEndDate(toDateOrNull(args.endDate)); | ||
| }, [args]); | ||
|
|
||
| const handleRangeChange = (start: Date | null, end: Date | null) => { | ||
| setStartDate(start); | ||
| setEndDate(end); | ||
| if ('onRangeChange' in args) args.onRangeChange?.(start, end); | ||
| }; | ||
|
|
||
| return ( | ||
| <Datepicker | ||
| isRange={true} | ||
| startDate={startDate} | ||
| endDate={endDate} | ||
| onRangeChange={handleRangeChange} | ||
| disabled={args.disabled} | ||
| className={args.className} | ||
| startPlaceholder={'startPlaceholder' in args ? args.startPlaceholder : undefined} | ||
| endPlaceholder={'endPlaceholder' in args ? args.endPlaceholder : undefined} | ||
| /> | ||
| ); | ||
| }; | ||
|
|
||
| /** | ||
| * 기본 Date Range | ||
| * | ||
| * 날짜 범위를 선택할 수 있는 Datepicker입니다. | ||
| * - 시작 날짜를 먼저 선택하고, 종료 날짜를 선택합니다. | ||
| * - 시작 날짜와 종료 날짜가 자동으로 정렬됩니다. | ||
| * - 범위 내의 날짜는 시각적으로 표시됩니다. | ||
| */ | ||
| export const DateRange: Story = { | ||
| render: (args) => <DateRangeExample {...args} />, | ||
| args: { | ||
| isRange: true, | ||
| onRangeChange: fn(), | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * 기본값이 있는 Date Range | ||
| * | ||
| * 초기 범위가 설정된 Date Range Picker입니다. | ||
| */ | ||
| export const DateRangeWithDefaultValue: Story = { | ||
| render: () => { | ||
| const today = new Date(); | ||
| const nextWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7); | ||
|
|
||
| return <DateRangeExample isRange={true} startDate={today} endDate={nextWeek} onRangeChange={fn()} />; | ||
| }, | ||
| }; | ||
|
|
||
| /** | ||
| * 비활성화된 Date Range | ||
| * | ||
| * 비활성화된 Date Range Picker입니다. | ||
| */ | ||
| export const DisabledDateRange: Story = { | ||
| render: () => { | ||
| const today = new Date(); | ||
| const nextWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7); | ||
|
|
||
| return ( | ||
| <DateRangeExample | ||
| isRange={true} | ||
| startDate={today} | ||
| endDate={nextWeek} | ||
| disabled={true} | ||
| startPlaceholder='시작 날짜' | ||
| endPlaceholder='종료 날짜' | ||
| onRangeChange={fn()} | ||
| /> | ||
| ); | ||
| }, | ||
| }; | ||
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,21 @@ | ||
| import { DatepickerContext } from './DatepickerContext'; | ||
| import DatepickerInput from './components/DatepickerInput'; | ||
| import DatepickerModal from './components/DatepickerModal'; | ||
| import * as S from './style.css'; | ||
| import { useDatepickerState } from './useDatepickerState'; | ||
| import type { DatepickerProps } from './types'; | ||
|
|
||
| function Datepicker(props: DatepickerProps) { | ||
| const contextValue = useDatepickerState(props); | ||
|
|
||
| return ( | ||
| <DatepickerContext.Provider value={contextValue}> | ||
| <div className={S.container}> | ||
| <DatepickerInput /> | ||
| <DatepickerModal /> | ||
| </div> | ||
| </DatepickerContext.Provider> | ||
| ); | ||
| } | ||
|
|
||
| export default Datepicker; |
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,48 @@ | ||
| import { createContext, useContext, type RefObject, type KeyboardEvent } from 'react'; | ||
|
|
||
| export interface DatepickerContextValue { | ||
| // state | ||
| isOpen: boolean; | ||
| isRange: boolean; | ||
| disabled: boolean; | ||
| internalValue: Date | null; | ||
| internalStartDate: Date | null; | ||
| internalEndDate: Date | null; | ||
| defaultSelectedDate: Date; | ||
| singleInputText: string; | ||
| startInputText: string; | ||
| endInputText: string; | ||
| anchorRect: DOMRect | null; | ||
|
|
||
| primaryInputRef: RefObject<HTMLInputElement>; | ||
|
|
||
| // props | ||
| placeholder?: string; | ||
| startPlaceholder?: string; | ||
| endPlaceholder?: string; | ||
|
|
||
| // setters | ||
| setSingleInputText: (value: string) => void; | ||
| setStartInputText: (value: string) => void; | ||
| setEndInputText: (value: string) => void; | ||
|
|
||
| // handlers | ||
| handleInputClick: () => void; | ||
| handleDateChange: (date: Date) => void; | ||
| handleRangeChange: (startDate: Date | null, endDate: Date | null) => void; | ||
| handleClose: () => void; | ||
| commitSingleInput: () => void; | ||
| commitRangeInput: () => void; | ||
| handleSingleInputKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void; | ||
| handleRangeInputKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void; | ||
| } | ||
|
|
||
| export const DatepickerContext = createContext<DatepickerContextValue | null>(null); | ||
|
|
||
| export function useDatepickerContext() { | ||
| const context = useContext(DatepickerContext); | ||
| if (!context) { | ||
| throw new Error('useDatepickerContext must be used within DatepickerContext.Provider'); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 다른 컴포넌트 에러 메시지에 맞게 문구 수정해주시면 좋을 것 같습니다! |
||
| } | ||
| return context; | ||
| } | ||
123 changes: 123 additions & 0 deletions
123
packages/ui/Datepicker/components/DatepickerDayView.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,123 @@ | ||
| import clsx from 'clsx'; | ||
| import { useMemo } from 'react'; | ||
| import { generateCalendarDates, isSameDate } from '../utils'; | ||
| import { DAYS_OF_WEEK, DATEPICKER_MODE } from '../constants'; | ||
| import type { DatepickerMode } from '../types'; | ||
| import * as S from '../style.css'; | ||
| import DatepickerHeader from './DatepickerHeader'; | ||
|
|
||
| interface DatepickerDayViewProps { | ||
| selectedDate: Date; | ||
| onDateSelect: (date: Date) => void; | ||
| onModeChange: (mode: DatepickerMode) => void; | ||
| onMonthChange: (date: Date) => void; | ||
|
|
||
| // range props | ||
| isRange?: boolean; | ||
| startDate?: Date | null; | ||
| endDate?: Date | null; | ||
| } | ||
|
|
||
| function DatepickerDayView({ | ||
| selectedDate, | ||
| onDateSelect, | ||
| onModeChange, | ||
| onMonthChange, | ||
| isRange = false, | ||
| startDate, | ||
| endDate, | ||
| }: DatepickerDayViewProps) { | ||
| const year = selectedDate.getFullYear(); | ||
| const month = selectedDate.getMonth(); | ||
|
|
||
| const today = useMemo(() => new Date(), []); | ||
| const dates = useMemo(() => generateCalendarDates(year, month), [year, month]); | ||
|
|
||
| const rangeCalculations = useMemo(() => { | ||
| const hasEndDate = Boolean(endDate); | ||
| const hasSameRangeDay = startDate && endDate ? isSameDate(startDate, endDate) : false; | ||
| const hasCompleteRange = Boolean(startDate && endDate && !hasSameRangeDay); | ||
|
|
||
| return { | ||
| hasEndDate, | ||
| hasSameRangeDay, | ||
| hasCompleteRange, | ||
| }; | ||
| }, [startDate, endDate]); | ||
|
|
||
| const handlePrevMonth = () => { | ||
| const prevMonth = new Date(year, month - 1, selectedDate.getDate()); | ||
| onMonthChange(prevMonth); | ||
| }; | ||
|
|
||
| const handleNextMonth = () => { | ||
| const nextMonth = new Date(year, month + 1, selectedDate.getDate()); | ||
| onMonthChange(nextMonth); | ||
| }; | ||
|
|
||
| const monthName = `${month + 1}월`; | ||
|
|
||
| return ( | ||
| <div> | ||
| <DatepickerHeader | ||
| onNextClick={handleNextMonth} | ||
| onPrevClick={handlePrevMonth} | ||
| onTitleClick={() => { | ||
| onModeChange(DATEPICKER_MODE.MONTH); | ||
| }} | ||
| showTitleIcon | ||
| title={`${year}년 ${monthName}`} | ||
| /> | ||
|
|
||
| <div className={S.dayHeaders}> | ||
| {DAYS_OF_WEEK.map((day) => ( | ||
| <div className={S.dayHeader} key={day}> | ||
| {day} | ||
| </div> | ||
| ))} | ||
| </div> | ||
|
|
||
| <div className={clsx(S.grid, S.dayGrid)}> | ||
| {dates.map((date, index) => { | ||
| const currentDate = new Date(date.year, date.month, date.day); | ||
| const isSelected = isSameDate(currentDate, selectedDate); | ||
| const isToday = isSameDate(currentDate, today); | ||
|
|
||
| const { hasEndDate, hasSameRangeDay, hasCompleteRange } = rangeCalculations; | ||
|
|
||
| const isCurrentStart = startDate ? isSameDate(currentDate, startDate) : false; | ||
| const isCurrentEnd = endDate ? isSameDate(currentDate, endDate) : false; | ||
|
|
||
| const isRangeStart = isRange && hasCompleteRange && isCurrentStart; | ||
| const isRangeEnd = isRange && hasCompleteRange && isCurrentEnd; | ||
| const isRangeStartOnly = isRange && isCurrentStart && (!hasEndDate || hasSameRangeDay); | ||
| const isInRange = | ||
| startDate && endDate && isRange && hasCompleteRange && currentDate > startDate && currentDate < endDate; | ||
|
|
||
| return ( | ||
| <button | ||
| className={clsx(S.cell, { | ||
| [S.cellOtherMonth]: !date.isCurrentMonth, | ||
| [S.cellSelected]: !isRange && isSelected, | ||
| [S.cellRangeStart]: isRangeStart, | ||
| [S.cellRangeStartOnly]: isRangeStartOnly, | ||
| [S.cellRangeEnd]: isRangeEnd, | ||
| [S.cellInRange]: isInRange, | ||
| })} | ||
| key={index} | ||
| onClick={() => { | ||
| onDateSelect(currentDate); | ||
| }} | ||
| type='button' | ||
| > | ||
| {date.day} | ||
| {isToday ? <span aria-hidden='true' className={S.todayIndicator} /> : null} | ||
| </button> | ||
| ); | ||
| })} | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| export default DatepickerDayView; |
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.
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.
useEffect 없이 동작할 수 있어야할 것 같아요! startDate, endDate prop 만으로!