Skip to content
TypeScript

feat: add Time tracking page

Vipul Kumar3e813d2b41a8
diff --git a/src/app/time-tracking/page.tsx b/src/app/time-tracking/page.tsx
new file mode 100644
index 0000000..e72cf91
--- /dev/null
+++ b/src/app/time-tracking/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { TimeTrackingPage } from "@/components/pages/time-tracking/time-tracking-page";
+
+export const metadata: Metadata = { title: "Time tracking" };
+
+export default function Page() {
+ return <TimeTrackingPage />;
+}
diff --git a/src/components/pages/time-tracking/entry-dialog.tsx b/src/components/pages/time-tracking/entry-dialog.tsx
new file mode 100644
index 0000000..26491e7
--- /dev/null
+++ b/src/components/pages/time-tracking/entry-dialog.tsx
@@ -0,0 +1,163 @@
+"use client";
+
+import { useState } from "react";
+import { Field } from "@/components/dialogs/field";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import type { TimeEntry } from "@/lib/types";
+import { useAppStore } from "@/stores/app-store";
+import { toast } from "sonner";
+import { formatHours } from "./shared";
+
+type Props = {
+ open: boolean;
+ session: number;
+ onClose: () => void;
+ entry?: TimeEntry;
+ defaultDate: string;
+ projects: string[];
+};
+
+export function EntryDialog({ open, session, onClose, entry, defaultDate, projects }: Props) {
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent className="gap-5 p-5 sm:max-w-[440px]">
+ <EntryForm key={session} entry={entry} defaultDate={defaultDate} projects={projects} onDone={onClose} />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function EntryForm({
+ entry,
+ defaultDate,
+ projects,
+ onDone,
+}: {
+ entry?: TimeEntry;
+ defaultDate: string;
+ projects: string[];
+ onDone: () => void;
+}) {
+ const saveTimeEntry = useAppStore((s) => s.saveTimeEntry);
+ const [date, setDate] = useState(entry?.date ?? defaultDate);
+ const [project, setProject] = useState(entry?.project ?? projects[0] ?? "");
+ const [task, setTask] = useState(entry?.task ?? "");
+ const [hours, setHours] = useState(String(entry ? Math.floor(entry.minutes / 60) : 1));
+ const [minutes, setMinutes] = useState(String(entry ? entry.minutes % 60 : 0));
+ const [billable, setBillable] = useState(entry?.billable ?? true);
+
+ const total = (Number(hours) || 0) * 60 + (Number(minutes) || 0);
+ const error =
+ total <= 0 ? "Log at least one minute." : total > 24 * 60 ? "An entry can't be longer than 24 hours." : null;
+
+ return (
+ <form
+ className="contents"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (error || !date || !project.trim() || !task.trim()) return;
+ saveTimeEntry({ id: entry?.id, date, project: project.trim(), task: task.trim(), minutes: total, billable });
+ toast.success(entry ? "Entry updated" : "Time logged", {
+ description: `${formatHours(total)} · ${project.trim()}`,
+ });
+ onDone();
+ }}
+ >
+ <DialogHeader className="gap-1.5">
+ <DialogTitle className="t-16">{entry ? "Edit entry" : "Add time entry"}</DialogTitle>
+ <DialogDescription className="t-14">
+ {entry ? "Update the details of this entry." : "Log time you forgot to track with the timer."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="grid gap-4">
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="Date" htmlFor="te-date">
+ <Input id="te-date" type="date" required value={date} onChange={(e) => setDate(e.target.value)} />
+ </Field>
+ <Field label="Project" htmlFor="te-project">
+ <Input
+ id="te-project"
+ required
+ list="te-projects"
+ placeholder="Project"
+ value={project}
+ onChange={(e) => setProject(e.target.value)}
+ />
+ <datalist id="te-projects">
+ {projects.map((p) => (
+ <option key={p} value={p} />
+ ))}
+ </datalist>
+ </Field>
+ </div>
+ <Field label="Task" htmlFor="te-task">
+ <Input
+ id="te-task"
+ required
+ autoFocus={!entry}
+ placeholder="What did you work on?"
+ value={task}
+ onChange={(e) => setTask(e.target.value)}
+ />
+ </Field>
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="Hours" htmlFor="te-hours">
+ <Input
+ id="te-hours"
+ type="number"
+ inputMode="numeric"
+ min={0}
+ max={24}
+ value={hours}
+ onChange={(e) => setHours(e.target.value)}
+ />
+ </Field>
+ <Field label="Minutes" htmlFor="te-minutes">
+ <Input
+ id="te-minutes"
+ type="number"
+ inputMode="numeric"
+ min={0}
+ max={59}
+ step={5}
+ value={minutes}
+ onChange={(e) => setMinutes(e.target.value)}
+ />
+ </Field>
+ </div>
+ <label className="flex items-center justify-between gap-3 rounded-lg border border-control bg-app px-3 py-2.5">
+ <span className="grid gap-1">
+ <span className="t-14 text-fg">Billable</span>
+ <span className="t-12 text-fg-2">Counts towards client invoices</span>
+ </span>
+ <Switch checked={billable} onCheckedChange={setBillable} />
+ </label>
+ {error && total !== 0 ? (
+ <p className="t-12 text-danger" role="alert">
+ {error}
+ </p>
+ ) : null}
+ </div>
+
+ <DialogFooter className="-mx-5 -mb-5 bg-app px-5 py-3">
+ <Button type="button" onClick={onDone}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="brand" disabled={!!error}>
+ {entry ? "Save changes" : `Log ${error ? "time" : formatHours(total)}`}
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/src/components/pages/time-tracking/shared.ts b/src/components/pages/time-tracking/shared.ts
new file mode 100644
index 0000000..6a973d5
--- /dev/null
+++ b/src/components/pages/time-tracking/shared.ts
@@ -0,0 +1,39 @@
+import type { EventColor, TimeEntry } from "@/lib/types";
+
+/** Validated two-series palette (brand + cyan, ΔE ≥ 10 under CVD in both themes). */
+export const BILLABLE_COLOR = "var(--brand)";
+export const NON_BILLABLE_COLOR = "#1f9cb8";
+
+const PROJECT_COLORS: EventColor[] = ["purple", "blue", "green", "orange", "pink", "cyan"];
+
+/** Stable color per project name so a project keeps its dot everywhere. */
+export function projectColor(name: string): EventColor {
+ let h = 0;
+ for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
+ return PROJECT_COLORS[h % PROJECT_COLORS.length];
+}
+
+export function sumMinutes(entries: TimeEntry[]) {
+ let total = 0;
+ let billable = 0;
+ for (const e of entries) {
+ total += e.minutes;
+ if (e.billable) billable += e.minutes;
+ }
+ return { total, billable, nonBillable: total - billable };
+}
+
+export function formatHours(minutes: number): string {
+ const h = Math.floor(minutes / 60);
+ const m = minutes % 60;
+ if (!h && !m) return "0h";
+ if (h && m) return `${h}h ${m}m`;
+ return h ? `${h}h` : `${m}m`;
+}
+
+/** 01:02:03 */
+export function formatClock(ms: number): string {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return `${pad(Math.floor(s / 3600))}:${pad(Math.floor((s % 3600) / 60))}:${pad(s % 60)}`;
+}
diff --git a/src/components/pages/time-tracking/time-tracking-page.tsx b/src/components/pages/time-tracking/time-tracking-page.tsx
new file mode 100644
index 0000000..b6544d5
--- /dev/null
+++ b/src/components/pages/time-tracking/time-tracking-page.tsx
@@ -0,0 +1,276 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { ClockIcon, PencilIcon, PlayIcon, PlusIcon, Trash2Icon } from "lucide-react";
+import { Icon } from "@/components/icon";
+import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { addDays, formatRange, formatShort, formatWeekday, isoWeek, startOfWeek } from "@/lib/dates";
+import type { TimeEntry } from "@/lib/types";
+import { useToday } from "@/hooks/use-today";
+import { useAppStore } from "@/stores/app-store";
+import { EntryDialog } from "./entry-dialog";
+import { BILLABLE_COLOR, formatHours, NON_BILLABLE_COLOR, projectColor, sumMinutes } from "./shared";
+import { TimerCard } from "./timer-card";
+import { ChartLegend, WeekChart, type DayTotal } from "./week-chart";
+
+type DialogState = { open: boolean; session: number; entry?: TimeEntry };
+
+export function TimeTrackingPage() {
+ const today = useToday();
+ const weekStartsOn = useAppStore((s) => s.settings.weekStartsOn);
+ const entries = useAppStore((s) => s.timeEntries);
+ const timerRunning = useAppStore((s) => s.timer.running);
+ const startTimer = useAppStore((s) => s.startTimer);
+ const saveTimeEntry = useAppStore((s) => s.saveTimeEntry);
+ const deleteTimeEntry = useAppStore((s) => s.deleteTimeEntry);
+
+ // Weeks relative to the current one, so the view follows `today` and `weekStartsOn`.
+ const [offset, setOffset] = useState(0);
+ const [dialog, setDialog] = useState<DialogState>({ open: false, session: 0 });
+
+ const weekStart = addDays(startOfWeek(today, weekStartsOn), offset * 7);
+ const weekEnd = addDays(weekStart, 6);
+ const isCurrentWeek = offset === 0;
+
+ const projects = useMemo(() => [...new Set(entries.map((e) => e.project))].sort(), [entries]);
+
+ const weekEntries = useMemo(
+ () => entries.filter((e) => e.date >= weekStart && e.date <= weekEnd),
+ [entries, weekStart, weekEnd],
+ );
+
+ const days: DayTotal[] = useMemo(
+ () =>
+ Array.from({ length: 7 }, (_, i) => {
+ const date = addDays(weekStart, i);
+ const t = sumMinutes(weekEntries.filter((e) => e.date === date));
+ return { date, billable: t.billable, nonBillable: t.nonBillable };
+ }),
+ [weekStart, weekEntries],
+ );
+
+ const groups = useMemo(() => {
+ const byDay = new Map<string, TimeEntry[]>();
+ for (const e of weekEntries) byDay.set(e.date, [...(byDay.get(e.date) ?? []), e]);
+ return [...byDay.entries()].sort((a, b) => b[0].localeCompare(a[0]));
+ }, [weekEntries]);
+
+ const totals = sumMinutes(weekEntries);
+ const todayMinutes = useMemo(
+ () => entries.reduce((n, e) => (e.date === today ? n + e.minutes : n), 0),
+ [entries, today],
+ );
+ const billablePct = totals.total ? Math.round((totals.billable / totals.total) * 100) : 0;
+
+ const openDialog = (entry?: TimeEntry) => setDialog((d) => ({ open: true, session: d.session + 1, entry }));
+ const scrollToDay = (date: string) =>
+ document.getElementById(`tt-day-${date}`)?.scrollIntoView({ behavior: "smooth", block: "start" });
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-thin bg-app">
+ <header className="sticky top-0 z-10 flex h-[68px] shrink-0 items-center gap-3 border-b border-hairline bg-surface px-4">
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <h2 className="t-16 text-fg">{isCurrentWeek ? "This week" : `Week ${isoWeek(weekStart)}`}</h2>
+ <p className="t-14 text-fg-2">
+ {formatRange(weekStart, weekEnd)} · {formatHours(totals.total)} logged
+ </p>
+ </div>
+ <div className="flex items-center gap-1">
+ <Button size="icon" aria-label="Previous week" onClick={() => setOffset((o) => o - 1)}>
+ <Icon name="arrow-left" />
+ </Button>
+ <Button disabled={isCurrentWeek} onClick={() => setOffset(0)}>
+ This week
+ </Button>
+ <Button size="icon" aria-label="Next week" onClick={() => setOffset((o) => o + 1)}>
+ <Icon name="arrow-left" className="rotate-180" />
+ </Button>
+ </div>
+ <div className="h-4 w-px bg-hairline" aria-hidden />
+ <Button variant="brand" onClick={() => openDialog()}>
+ <PlusIcon /> Add entry
+ </Button>
+ </header>
+
+ <div className="flex flex-col gap-4 p-4">
+ <TimerCard projects={projects} todayMinutes={todayMinutes} />
+
+ <section className="grid grid-cols-[1fr_260px] overflow-hidden rounded-xl border border-hairline bg-surface">
+ <div className="flex flex-col gap-5 p-4">
+ <div className="flex items-center justify-between">
+ <h3 className="t-14 text-fg">Hours per day</h3>
+ <ChartLegend />
+ </div>
+ <WeekChart days={days} today={today} onSelectDay={scrollToDay} />
+ </div>
+ <dl className="flex flex-col border-l border-hairline">
+ <Stat label="Total" value={formatHours(totals.total)} />
+ <Stat label="Billable" value={formatHours(totals.billable)} color={BILLABLE_COLOR} />
+ <Stat label="Non-billable" value={formatHours(totals.nonBillable)} color={NON_BILLABLE_COLOR} />
+ <div className="mt-auto flex flex-col gap-2 border-t border-hairline p-4">
+ <div className="flex items-center justify-between">
+ <span className="t-12 text-fg-2">Billable ratio</span>
+ <span className="t-12 text-fg tabular-nums">{billablePct}%</span>
+ </div>
+ <div className="flex h-1.5 gap-[2px] overflow-hidden rounded-full bg-app">
+ {totals.billable > 0 && (
+ <span className="h-full" style={{ width: `${billablePct}%`, background: BILLABLE_COLOR }} />
+ )}
+ {totals.nonBillable > 0 && (
+ <span className="h-full flex-1" style={{ background: NON_BILLABLE_COLOR }} />
+ )}
+ </div>
+ </div>
+ </dl>
+ </section>
+
+ <section className="overflow-hidden rounded-xl border border-hairline bg-surface">
+ <div className="flex h-12 items-center justify-between border-b border-hairline px-4">
+ <h3 className="t-14 text-fg">Entries</h3>
+ <span className="t-12 text-fg-2">
+ {weekEntries.length} {weekEntries.length === 1 ? "entry" : "entries"}
+ </span>
+ </div>
+ {groups.length === 0 ? (
+ <div className="flex flex-col items-center gap-3 px-4 py-14 text-center">
+ <span className="flex size-10 items-center justify-center rounded-lg bg-app">
+ <ClockIcon className="size-4 text-icon" />
+ </span>
+ <div className="flex flex-col gap-1.5">
+ <p className="t-14 text-fg">No time logged this week</p>
+ <p className="t-14 text-fg-2">Start the timer or add an entry manually.</p>
+ </div>
+ <Button onClick={() => openDialog()}>
+ <PlusIcon /> Add entry
+ </Button>
+ </div>
+ ) : (
+ <table className="w-full table-fixed border-collapse">
+ <colgroup>
+ <col />
+ <col className="w-[200px]" />
+ <col className="w-[110px]" />
+ <col className="w-[100px]" />
+ <col className="w-[112px]" />
+ </colgroup>
+ <thead>
+ <tr className="h-10 bg-app text-left">
+ <th className="t-14 px-4 font-medium text-fg-2">Task</th>
+ <th className="t-14 px-2 font-medium text-fg-2">Project</th>
+ <th className="t-14 px-2 font-medium text-fg-2">Billable</th>
+ <th className="t-14 px-2 text-right font-medium text-fg-2">Duration</th>
+ <th className="px-4">
+ <span className="sr-only">Actions</span>
+ </th>
+ </tr>
+ </thead>
+ {groups.map(([date, list]) => (
+ <tbody key={date}>
+ <tr id={`tt-day-${date}`} className="h-9 scroll-mt-[76px] border-y border-subtle bg-surface">
+ <th colSpan={3} className="px-4 text-left font-medium">
+ <span className="t-12 text-fg">{formatWeekday(date)}</span>
+ <span className="t-12 ml-1.5 text-fg-2">
+ {formatShort(date)}
+ {date === today && " · Today"}
+ </span>
+ </th>
+ <td className="t-12 px-2 text-right text-fg-2 tabular-nums">
+ {formatHours(list.reduce((n, e) => n + e.minutes, 0))}
+ </td>
+ <td />
+ </tr>
+ {list.map((e) => (
+ <tr key={e.id} className="h-14 border-b border-subtle transition-colors duration-150 hover-fine:bg-hover/50">
+ <td className="t-14 truncate px-4 text-table">{e.task}</td>
+ <td className="px-2">
+ <span className="t-14 flex min-w-0 items-center gap-2 text-table">
+ <span
+ className="size-2 shrink-0 rounded-full"
+ style={{ background: `var(--event-${projectColor(e.project)}-fg)` }}
+ />
+ <span className="truncate">{e.project}</span>
+ </span>
+ </td>
+ <td className="px-2">
+ <Switch
+ size="sm"
+ checked={e.billable}
+ aria-label={`Billable: ${e.task}`}
+ onCheckedChange={(v) => saveTimeEntry({ ...e, billable: v })}
+ />
+ </td>
+ <td className="t-14 px-2 text-right text-table tabular-nums">{formatHours(e.minutes)}</td>
+ <td className="px-4">
+ <div className="flex items-center justify-end gap-0.5">
+ <RowAction
+ label="Resume timer"
+ disabled={timerRunning}
+ onClick={() => startTimer(e.project, e.task)}
+ >
+ <PlayIcon />
+ </RowAction>
+ <RowAction label="Edit entry" onClick={() => openDialog(e)}>
+ <PencilIcon />
+ </RowAction>
+ <RowAction label="Delete entry" onClick={() => deleteTimeEntry(e.id)}>
+ <Trash2Icon />
+ </RowAction>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ ))}
+ </table>
+ )}
+ </section>
+ </div>
+
+ <EntryDialog
+ open={dialog.open}
+ session={dialog.session}
+ entry={dialog.entry}
+ defaultDate={today >= weekStart && today <= weekEnd ? today : weekStart}
+ projects={projects}
+ onClose={() => setDialog((d) => ({ ...d, open: false }))}
+ />
+ </div>
+ );
+}
+
+function Stat({ label, value, color }: { label: string; value: string; color?: string }) {
+ return (
+ <div className="flex flex-col gap-2 border-b border-hairline px-4 py-3.5 last:border-b-0">
+ <dt className="t-12 flex items-center gap-1.5 text-fg-2">
+ {color && <span className="size-2 rounded-[2px]" style={{ background: color }} />}
+ {label}
+ </dt>
+ <dd className="text-[20px] leading-none font-medium tracking-[-0.4px] text-fg tabular-nums">{value}</dd>
+ </div>
+ );
+}
+
+function RowAction({
+ label,
+ onClick,
+ disabled,
+ children,
+}: {
+ label: string;
+ onClick: () => void;
+ disabled?: boolean;
+ children: React.ReactNode;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon-sm" aria-label={label} disabled={disabled} onClick={onClick}>
+ {children}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/src/components/pages/time-tracking/timer-card.tsx b/src/components/pages/time-tracking/timer-card.tsx
new file mode 100644
index 0000000..05bf834
--- /dev/null
+++ b/src/components/pages/time-tracking/timer-card.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { PlayIcon, SquareIcon } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { cn } from "@/lib/utils";
+import { useAppStore } from "@/stores/app-store";
+import { formatClock, formatHours } from "./shared";
+
+/** Ticks once a second while the timer runs; `useNow()` only refreshes every 30s. */
+function useElapsed(running: boolean, startedAt: number | null): number {
+ const [now, setNow] = useState(0);
+ useEffect(() => {
+ if (!running) return;
+ const tick = () => setNow(Date.now());
+ const raf = requestAnimationFrame(tick);
+ const id = setInterval(tick, 1000);
+ return () => {
+ cancelAnimationFrame(raf);
+ clearInterval(id);
+ };
+ }, [running]);
+ if (!running || !startedAt || !now) return 0;
+ return Math.max(0, now - startedAt);
+}
+
+export function TimerCard({ projects, todayMinutes }: { projects: string[]; todayMinutes: number }) {
+ const timer = useAppStore((s) => s.timer);
+ const startTimer = useAppStore((s) => s.startTimer);
+ const stopTimer = useAppStore((s) => s.stopTimer);
+ const updateTimer = useAppStore((s) => s.updateTimer);
+ const elapsed = useElapsed(timer.running, timer.startedAt);
+
+ const start = () => startTimer(timer.project.trim() || "General", timer.task.trim());
+
+ return (
+ <section
+ aria-label="Timer"
+ className={cn(
+ "flex items-center gap-3 rounded-xl border bg-surface p-3 transition-[border-color] duration-200 ease-(--ease-out)",
+ timer.running ? "border-brand/40" : "border-hairline",
+ )}
+ >
+ <form
+ className="flex min-w-0 flex-1 items-center gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (timer.running) stopTimer();
+ else start();
+ }}
+ >
+ <Input
+ aria-label="Project"
+ placeholder="Project"
+ list="tt-projects"
+ className="h-[30px] w-52"
+ value={timer.project}
+ onChange={(e) => updateTimer({ project: e.target.value })}
+ />
+ <Input
+ aria-label="Task"
+ placeholder="What are you working on?"
+ className="h-[30px] min-w-0 flex-1"
+ value={timer.task}
+ onChange={(e) => updateTimer({ task: e.target.value })}
+ />
+ <datalist id="tt-projects">
+ {projects.map((p) => (
+ <option key={p} value={p} />
+ ))}
+ </datalist>
+ <div className="flex shrink-0 items-center gap-3 pl-2">
+ <div className="flex flex-col items-end gap-1.5">
+ <span
+ className={cn(
+ "text-[22px] leading-none font-medium tracking-[-0.44px] tabular-nums",
+ timer.running ? "text-fg" : "text-placeholder",
+ )}
+ role="timer"
+ aria-live="off"
+ >
+ {formatClock(elapsed)}
+ </span>
+ <span className="t-12 flex items-center gap-1.5 text-fg-2">
+ {timer.running ? (
+ <>
+ <span className="size-1.5 animate-pulse rounded-full bg-danger" aria-hidden />
+ Recording
+ </>
+ ) : (
+ <>Today · {formatHours(todayMinutes)}</>
+ )}
+ </span>
+ </div>
+ {timer.running ? (
+ <Button type="submit" variant="destructive" className="w-[84px]">
+ <SquareIcon className="fill-current" /> Stop
+ </Button>
+ ) : (
+ <Button type="submit" variant="brand" className="w-[84px]">
+ <PlayIcon className="fill-current" /> Start
+ </Button>
+ )}
+ </div>
+ </form>
+ </section>
+ );
+}
diff --git a/src/components/pages/time-tracking/week-chart.tsx b/src/components/pages/time-tracking/week-chart.tsx
new file mode 100644
index 0000000..b1c8222
--- /dev/null
+++ b/src/components/pages/time-tracking/week-chart.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { formatWeekday, fromKey, WEEKDAYS_SHORT } from "@/lib/dates";
+import { cn } from "@/lib/utils";
+import { BILLABLE_COLOR, formatHours, NON_BILLABLE_COLOR } from "./shared";
+
+export type DayTotal = { date: string; billable: number; nonBillable: number };
+
+const PLOT_HEIGHT = 132;
+const TARGET = 8 * 60;
+
+export function WeekChart({
+ days,
+ today,
+ onSelectDay,
+}: {
+ days: DayTotal[];
+ today: string;
+ onSelectDay: (date: string) => void;
+}) {
+ const max = Math.max(TARGET, ...days.map((d) => d.billable + d.nonBillable));
+ const px = (minutes: number) => Math.round((minutes / max) * PLOT_HEIGHT);
+ const targetY = px(TARGET);
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="relative" style={{ height: PLOT_HEIGHT + 20 }}>
+ {/* 8h reference line */}
+ <div
+ aria-hidden
+ className="absolute inset-x-0 border-t border-dashed border-hairline"
+ style={{ bottom: targetY }}
+ >
+ <span className="t-12 absolute -top-2 right-0 bg-surface pl-1.5 text-section">8h</span>
+ </div>
+ <div aria-hidden className="absolute inset-x-0 bottom-0 border-t border-hairline" />
+ <div className="relative grid h-full grid-cols-7 gap-2 pr-6">
+ {days.map((d) => {
+ const total = d.billable + d.nonBillable;
+ const bH = px(d.billable);
+ const nH = px(d.nonBillable);
+ return (
+ <Tooltip key={d.date}>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => onSelectDay(d.date)}
+ disabled={!total}
+ aria-label={`${formatWeekday(d.date)}: ${formatHours(total)}`}
+ className="group flex h-full flex-col items-center justify-end rounded-md outline-none focus-visible:ring-3 focus-visible:ring-brand/15 disabled:cursor-default"
+ >
+ {total > 0 && (
+ <span className="t-12 mb-1.5 text-fg-2 tabular-nums transition-colors duration-150 group-hover:text-fg">
+ {formatHours(total)}
+ </span>
+ )}
+ <span className="flex w-7 flex-col justify-end gap-[2px]">
+ {nH > 0 && (
+ <span
+ className="block w-full rounded-t-[4px]"
+ style={{ height: Math.max(nH, 2), background: NON_BILLABLE_COLOR }}
+ />
+ )}
+ {bH > 0 && (
+ <span
+ className={cn("block w-full", nH > 0 ? "" : "rounded-t-[4px]")}
+ style={{ height: Math.max(bH, 2), background: BILLABLE_COLOR }}
+ />
+ )}
+ </span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4} className="flex-col items-start gap-1.5 py-2">
+ <span className="t-12 opacity-70">{formatWeekday(d.date)}</span>
+ <span className="t-12 flex items-center gap-1.5">
+ <span className="size-2 rounded-[2px]" style={{ background: BILLABLE_COLOR }} />
+ Billable {formatHours(d.billable)}
+ </span>
+ <span className="t-12 flex items-center gap-1.5">
+ <span className="size-2 rounded-[2px]" style={{ background: NON_BILLABLE_COLOR }} />
+ Non-billable {formatHours(d.nonBillable)}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ </div>
+ <div className="grid grid-cols-7 gap-2 pr-6">
+ {days.map((d) => {
+ const isToday = d.date === today;
+ return (
+ <div key={d.date} className="flex flex-col items-center gap-1.5">
+ <span className={cn("t-12-tight", isToday ? "text-brand" : "text-dayname")}>
+ {WEEKDAYS_SHORT[fromKey(d.date).getDay()]}
+ </span>
+ <span
+ className={cn(
+ "t-14 flex size-6 items-center justify-center rounded-md",
+ isToday ? "accent-badge" : "text-fg",
+ )}
+ >
+ {fromKey(d.date).getDate()}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+export function ChartLegend() {
+ return (
+ <div className="flex items-center gap-3">
+ <span className="t-12 flex items-center gap-1.5 text-fg-2">
+ <span className="size-2 rounded-[2px]" style={{ background: BILLABLE_COLOR }} /> Billable
+ </span>
+ <span className="t-12 flex items-center gap-1.5 text-fg-2">
+ <span className="size-2 rounded-[2px]" style={{ background: NON_BILLABLE_COLOR }} /> Non-billable
+ </span>
+ </div>
+ );
+}