RippleWorkers / src /components /dashboard /TimePicker.tsx
damndeepesh
Initialize project with LavinMQ integration and Docker support
c7fbc2e
Raw History Blame Contribute Delete
3.34 kB
import { useEffect, useState } from "react";
import { ChevronUp, ChevronDown } from "lucide-react";
interface TimePickerProps {
date: Date | null;
onChange: (date: Date) => void;
}
export default function TimePicker({ date, onChange }: TimePickerProps) {
// Default to current time if no date provided, but don't fire change until user interacts
const [localDate, setLocalDate] = useState<Date>(date || new Date());
useEffect(() => {
if (date) {
setLocalDate(date);
}
}, [date]);
const updateTime = (type: "hour" | "minute" | "ampm", value: number | string) => {
const newDate = new Date(localDate);
let hours = newDate.getHours();
let minutes = newDate.getMinutes();
if (type === "hour") {
const val = value as number;
// Convert 12h to 24h
const isPM = hours >= 12;
if (isPM) {
hours = val === 12 ? 12 : val + 12;
} else {
hours = val === 12 ? 0 : val;
}
} else if (type === "minute") {
minutes = value as number;
} else if (type === "ampm") {
const isPM = value === "PM";
if (isPM && hours < 12) hours += 12;
if (!isPM && hours >= 12) hours -= 12;
}
newDate.setHours(hours, minutes);
setLocalDate(newDate);
onChange(newDate); // Propagate change
};
// Derived Display Values
const hours24 = localDate.getHours();
const displayHour = hours24 % 12 || 12;
const minutes = localDate.getMinutes();
const ampm = hours24 >= 12 ? "PM" : "AM";
return (
<div className="flex items-center gap-1 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-700 rounded-lg p-1 px-2 shadow-sm">
{/* Hour */}
<select
value={displayHour}
onChange={(e) => updateTime("hour", parseInt(e.target.value))}
className="bg-transparent text-sm font-bold text-gray-900 dark:text-white outline-none appearance-none cursor-pointer text-center w-8"
>
{Array.from({ length: 12 }, (_, i) => i + 1).map(h => (
<option key={h} value={h}>{h}</option>
))}
</select>
<span className="text-gray-400 font-bold">:</span>
{/* Minute */}
<select
value={minutes}
onChange={(e) => updateTime("minute", parseInt(e.target.value))}
className="bg-transparent text-sm font-bold text-gray-900 dark:text-white outline-none appearance-none cursor-pointer text-center w-8"
>
{Array.from({ length: 60 }, (_, i) => i).map(m => (
<option key={m} value={m}>{m.toString().padStart(2, '0')}</option>
))}
</select>
{/* AM/PM */}
<button
type="button"
onClick={() => updateTime("ampm", ampm === "AM" ? "PM" : "AM")}
className="ml-1 text-xs font-bold text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors bg-gray-100 dark:bg-zinc-800 px-1.5 py-0.5 rounded"
>
{ampm}
</button>
</div>
);
}