Skip to content

Commit

Permalink
imprv: DatePicker component initial value logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jaieds committed Dec 30, 2024
1 parent 492e3ef commit 0d3eacb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/components/datepicker/datepicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
subWeeks,
subMonths,
} from 'date-fns';
import { getDefaultSelectedValue } from './utils';

export interface DatePickerProps {
/** Defines the selection selectionType of the date picker: single, range, or multiple dates. */
Expand Down Expand Up @@ -54,15 +55,24 @@ const DatePicker = ( {
const [ selectedDates, setSelectedDates ] = useState<
TDateRange | Date | Date[] | null
>( () => {
if ( selected ) {
return selected;
if ( ! selected ) {
return getDefaultSelectedValue( selectionType );
}
if ( selectionType === 'multiple' ) {
return [];
} else if ( selectionType === 'range' ) {
return { from: null, to: null };

// Type guards for different selection types
const isValidMultiple =
selectionType === 'multiple' && Array.isArray( selected );
const isValidRange =
selectionType === 'range' && 'from' in selected && 'to' in selected;
const isValidSingle =
selectionType === 'single' && selected instanceof Date;

// Return selected if valid, otherwise return default value
if ( isValidMultiple || isValidRange || isValidSingle ) {
return selected;
}
return null;

return getDefaultSelectedValue( selectionType );
} );

const handleSelect = ( selectedDate: Date | Date[] | TDateRange | null ) => {
Expand Down
10 changes: 10 additions & 0 deletions src/components/datepicker/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,13 @@ export const formatWeekdayName = ( date: Date ) => {
export const generateYearRange = ( start: number, count = 24 ) => {
return Array.from( { length: count }, ( _, i ) => start + i );
};

export const getDefaultSelectedValue = ( type: string ) => {
if ( type === 'multiple' ) {
return [];
}
if ( type === 'range' ) {
return { from: null, to: null };
}
return null;
};

0 comments on commit 0d3eacb

Please sign in to comment.