Skip to content

Commit

Permalink
Simplify timepicker to use string and fix typing
Browse files Browse the repository at this point in the history
  • Loading branch information
nighto committed Dec 10, 2024
1 parent a59b77c commit d5aa79d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
.bk-timepicker {
@include bk.component-base(bk-timepicker);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,13 @@ export default {
export const TimePickerStory: Story = {
name: 'Time Picker',
render: (args) => {
const [date, setDate] = React.useState<Date>(new Date());
const [time, setTime] = React.useState<string>(`${new Date().getHours()}:${new Date().getMinutes()}`);

return (
<div>
<TimePicker date={date} onUpdate={setDate}/>
<TimePicker time={time} onUpdate={setTime}/>
<p>
The selected time is:&nbsp;
{date.getHours().toString().padStart(2, '0')}:{date.getMinutes().toString().padStart(2, '0')}
The selected time is: {time}
</p>
</div>
);
Expand Down
20 changes: 6 additions & 14 deletions src/components/forms/controls/TimePicker/TimePicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,17 @@ export type TimePickerProps = ComponentProps<'input'> & {
/** An optional class name to be appended to the class list. */
className?: ClassNameArgument,

/** The date object to show / manipulate the time. */
date: Date,
/** A time string as defined to be used by input type="time", with the hh:mm format. */
time: string,

/** A callback function to update the time. */
onUpdate: (date: Date) => void,
onUpdate: (time: string) => void,
};

export const TimePicker = ({ unstyled = false, className, date, onUpdate, ...propsRest }: TimePickerProps) => {
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const time = `${hours}:${minutes}`;

export const TimePicker = ({ unstyled = false, className, time, onUpdate, ...propsRest }: TimePickerProps) => {
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newTimeString = e.target.value;
const [newHours, newMinutes] = newTimeString.split(':');
const newDate = new Date(date);
newDate.setHours(Number(newHours));
newDate.setMinutes(Number(newMinutes));
onUpdate(newDate);
onUpdate(newTimeString);
};

return (
Expand All @@ -48,4 +40,4 @@ export const TimePicker = ({ unstyled = false, className, date, onUpdate, ...pro
<Input type="time" value={time} onChange={onChange} {...propsRest} />
</div>
);
};
};

0 comments on commit d5aa79d

Please sign in to comment.