TypeScript
feat: add global dialogs for leave requests and events
Vipul Kumar6ddaa87a5ad7
diff --git a/src/components/calendar/event-colors.ts b/src/components/calendar/event-colors.tsnew file mode 100644index 0000000..86da025--- /dev/null+++ b/src/components/calendar/event-colors.ts@@ -0,0 +1,8 @@+import type { EventColor } from "@/lib/types";++export const EVENT_COLORS: EventColor[] = ["blue", "cyan", "green", "orange", "pink", "purple"];++/** Inline style for an event surface using the design's paired bg/fg tokens. */+export function eventStyle(color: EventColor): React.CSSProperties {+ return { background: `var(--event-${color}-bg)`, color: `var(--event-${color}-fg)` };+}diff --git a/src/components/dialogs/event-dialog.tsx b/src/components/dialogs/event-dialog.tsxnew file mode 100644index 0000000..8d34422--- /dev/null+++ b/src/components/dialogs/event-dialog.tsx@@ -0,0 +1,249 @@+"use client";++import { useState } from "react";+import { CopyIcon, Trash2Icon } from "lucide-react";+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 { Textarea } from "@/components/ui/textarea";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { EVENT_COLORS } from "@/components/calendar/event-colors";+import { parseTime, timeInputValue } from "@/lib/dates";+import { cn } from "@/lib/utils";+import type { CalEvent, EventColor } from "@/lib/types";+import { useAppStore } from "@/stores/app-store";+import { Field } from "./field";++type Props = {+ open: boolean;+ session: number;+ onClose: () => void;+ eventId?: string;+ date?: string;+ start?: number;+ end?: number;+ allDay?: boolean;+};++export function EventDialog({ open, session, onClose, ...payload }: Props) {+ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-5 p-5 sm:max-w-[440px]">+ <EventForm key={session} {...payload} onDone={onClose} />+ </DialogContent>+ </Dialog>+ );+}++type Draft = Omit<CalEvent, "id">;++function EventForm({+ eventId,+ date,+ start,+ end,+ allDay,+ onDone,+}: Omit<Props, "open" | "session" | "onClose"> & { onDone: () => void }) {+ const existing = useAppStore((s) => s.events.find((e) => e.id === eventId));+ const saveEvent = useAppStore((s) => s.saveEvent);+ const deleteEvent = useAppStore((s) => s.deleteEvent);+ const duplicateEvent = useAppStore((s) => s.duplicateEvent);++ const [draft, setDraft] = useState<Draft>(() =>+ existing+ ? { ...existing }+ : {+ title: "",+ date: date ?? "",+ start: start ?? 540,+ end: end ?? (start ?? 540) + 60,+ allDay: allDay ?? false,+ color: "blue",+ note: "",+ location: "",+ },+ );+ const set = <K extends keyof Draft>(k: K, v: Draft[K]) => setDraft((d) => ({ ...d, [k]: v }));++ const error = !draft.allDay && draft.end <= draft.start ? "End time must be after the start time." : null;+ const linked = Boolean(existing?.requestId);++ return (+ <form+ className="contents"+ onSubmit={(e) => {+ e.preventDefault();+ if (error || !draft.title.trim() || !draft.date) return;+ saveEvent({+ ...draft,+ id: existing?.id,+ title: draft.title.trim(),+ start: draft.allDay ? 0 : draft.start,+ end: draft.allDay ? 1440 : draft.end,+ });+ onDone();+ }}+ >+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">{existing ? "Edit event" : "New event"}</DialogTitle>+ <DialogDescription className="t-14">+ {linked ? "This event belongs to a leave request." : "Add it to your calendar — only you can see it."}+ </DialogDescription>+ </DialogHeader>++ <div className="grid gap-4">+ <Field label="Title" htmlFor="ev-title">+ <Input+ id="ev-title"+ autoFocus+ required+ placeholder="e.g. Dentist appointment"+ value={draft.title}+ onChange={(e) => set("title", e.target.value)}+ />+ </Field>++ <div className="grid grid-cols-[1.4fr_1fr_1fr] items-end gap-3">+ <Field label="Date" htmlFor="ev-date">+ <Input id="ev-date" type="date" required value={draft.date} onChange={(e) => set("date", e.target.value)} />+ </Field>+ <Field label="Start" htmlFor="ev-start">+ <Input+ id="ev-start"+ type="time"+ step={900}+ disabled={draft.allDay}+ value={timeInputValue(draft.start)}+ onChange={(e) => {+ const next = parseTime(e.target.value);+ const length = draft.end - draft.start;+ setDraft((d) => ({ ...d, start: next, end: Math.min(1440, next + Math.max(15, length)) }));+ }}+ />+ </Field>+ <Field label="End" htmlFor="ev-end">+ <Input+ id="ev-end"+ type="time"+ step={900}+ disabled={draft.allDay}+ value={timeInputValue(draft.end)}+ onChange={(e) => set("end", parseTime(e.target.value) || 1440)}+ />+ </Field>+ </div>+ {error && (+ <p className="t-12 -mt-2 text-danger" role="alert">+ {error}+ </p>+ )}++ <div className="flex items-center justify-between gap-3">+ <label className="flex cursor-pointer items-center gap-2.5">+ <Switch checked={draft.allDay} onCheckedChange={(v) => set("allDay", v)} />+ <span className="t-14 text-fg">All day</span>+ </label>+ <div className="flex items-center gap-1.5" role="radiogroup" aria-label="Color">+ {EVENT_COLORS.map((c) => (+ <ColorSwatch key={c} color={c} selected={draft.color === c} onSelect={() => set("color", c)} />+ ))}+ </div>+ </div>++ <Field label="Location" htmlFor="ev-location">+ <Input+ id="ev-location"+ placeholder="Add a place or a link"+ value={draft.location ?? ""}+ onChange={(e) => set("location", e.target.value)}+ />+ </Field>++ <Field label="Notes" htmlFor="ev-note" hint="Short notes show on the event in the calendar.">+ <Textarea id="ev-note" rows={2} value={draft.note ?? ""} onChange={(e) => set("note", e.target.value)} />+ </Field>+ </div>++ <DialogFooter className="-mx-5 -mb-5 items-center bg-app px-5 py-3 sm:justify-between">+ <div className="flex gap-1">+ {existing && (+ <>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label="Delete event"+ onClick={() => {+ deleteEvent(existing.id);+ onDone();+ }}+ >+ <Trash2Icon className="text-danger" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Delete</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label="Duplicate event"+ onClick={() => {+ duplicateEvent(existing.id);+ onDone();+ }}+ >+ <CopyIcon />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Duplicate</TooltipContent>+ </Tooltip>+ </>+ )}+ </div>+ <div className="flex gap-2">+ <Button type="button" onClick={onDone}>+ Cancel+ </Button>+ <Button type="submit" variant="brand" disabled={!!error || !draft.title.trim()}>+ {existing ? "Save" : "Create event"}+ </Button>+ </div>+ </DialogFooter>+ </form>+ );+}++function ColorSwatch({ color, selected, onSelect }: { color: EventColor; selected: boolean; onSelect: () => void }) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ aria-label={color}+ onClick={onSelect}+ className={cn(+ "press size-5 rounded-full outline-none ring-offset-2 ring-offset-surface focus-visible:ring-2 focus-visible:ring-brand/50",+ selected && "ring-2",+ )}+ style={{+ background: `var(--event-${color}-bg)`,+ boxShadow: `inset 0 0 0 1.5px var(--event-${color}-fg)`,+ ...(selected ? ({ "--tw-ring-color": `var(--event-${color}-fg)` } as React.CSSProperties) : {}),+ }}+ />+ );+}diff --git a/src/components/dialogs/field.tsx b/src/components/dialogs/field.tsxnew file mode 100644index 0000000..b4370d5--- /dev/null+++ b/src/components/dialogs/field.tsx@@ -0,0 +1,39 @@+import { Label } from "@/components/ui/label";+import { cn } from "@/lib/utils";++/** Label + control + optional hint/error, the building block of every form. */+export function Field({+ label,+ htmlFor,+ hint,+ error,+ className,+ children,+}: {+ label: string;+ htmlFor?: string;+ hint?: React.ReactNode;+ error?: string | null;+ className?: string;+ children: React.ReactNode;+}) {+ return (+ <div className={cn("grid gap-2", className)}>+ <Label htmlFor={htmlFor} className="t-12 font-medium text-fg-2">+ {label}+ </Label>+ {children}+ {error ? (+ <p className="t-12 text-danger" role="alert">+ {error}+ </p>+ ) : hint ? (+ <p className="t-12 leading-[1.35] text-fg-2">{hint}</p>+ ) : null}+ </div>+ );+}++export function DialogSection({ className, children }: { className?: string; children: React.ReactNode }) {+ return <div className={cn("grid gap-4", className)}>{children}</div>;+}diff --git a/src/components/dialogs/global-dialogs.tsx b/src/components/dialogs/global-dialogs.tsxnew file mode 100644index 0000000..bfcb0d6--- /dev/null+++ b/src/components/dialogs/global-dialogs.tsx@@ -0,0 +1,64 @@+"use client";++import { useState } from "react";+import { useOverlayStore, type Overlay } from "@/stores/overlay-store";+import { EventDialog } from "./event-dialog";+import { HolidaysDialog, PolicyDialog, ShortcutsDialog } from "./info-dialogs";+import { RequestDetailsDialog } from "./request-details-dialog";+import { RequestDialog } from "./request-dialog";++type Kind = Exclude<Overlay["kind"], "none" | "search">;+type Latest = { [K in Kind]?: Extract<Overlay, { kind: K }> };++/**+ * Hosts every app-wide dialog. The last payload of each kind is kept around so+ * a dialog keeps its content while it animates out after closing.+ */+export function GlobalDialogs() {+ const overlay = useOverlayStore((s) => s.overlay);+ const close = useOverlayStore((s) => s.close);+ const [latest, setLatest] = useState<Latest>({});+ const [session, setSession] = useState(0);+ const [prev, setPrev] = useState<Overlay>(overlay);++ // Derive state during render (no effect): remember payloads and count opens.+ if (overlay !== prev) {+ setPrev(overlay);+ if (overlay.kind !== "none" && overlay.kind !== "search") {+ setLatest((l) => ({ ...l, [overlay.kind]: overlay }));+ setSession((n) => n + 1);+ }+ }++ const is = (k: Kind) => overlay.kind === k;++ return (+ <>+ <RequestDialog+ open={is("request")}+ session={session}+ onClose={close}+ requestId={latest.request?.requestId}+ from={latest.request?.from}+ />+ <EventDialog+ open={is("event")}+ session={session}+ onClose={close}+ eventId={latest.event?.eventId}+ date={latest.event?.date}+ start={latest.event?.start}+ end={latest.event?.end}+ allDay={latest.event?.allDay}+ />+ <RequestDetailsDialog+ open={is("request-details")}+ onClose={close}+ requestId={latest["request-details"]?.requestId}+ />+ <HolidaysDialog open={is("holidays")} onClose={close} />+ <PolicyDialog open={is("policy")} onClose={close} />+ <ShortcutsDialog open={is("shortcuts")} onClose={close} />+ </>+ );+}diff --git a/src/components/dialogs/info-dialogs.tsx b/src/components/dialogs/info-dialogs.tsxnew file mode 100644index 0000000..0795fa7--- /dev/null+++ b/src/components/dialogs/info-dialogs.tsx@@ -0,0 +1,226 @@+"use client";++import { useRouter } from "next/navigation";+import { useState } from "react";+import { PlusIcon, Trash2Icon } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { ScrollArea } from "@/components/ui/scroll-area";+import { SHORTCUTS } from "@/components/shell/keyboard-shortcuts";+import { formatWeekday, MONTHS } from "@/lib/dates";+import { computeLeaveStats, formatDays } from "@/lib/leave";+import { cn } from "@/lib/utils";+import { useToday } from "@/hooks/use-today";+import { useAppStore } from "@/stores/app-store";+import { useCalendarStore } from "@/stores/calendar-store";++type BaseProps = { open: boolean; onClose: () => void };++export function HolidaysDialog({ open, onClose }: BaseProps) {+ const router = useRouter();+ const today = useToday();+ const holidays = useAppStore((s) => s.holidays);+ const addHoliday = useAppStore((s) => s.addHoliday);+ const removeHoliday = useAppStore((s) => s.removeHoliday);+ const [adding, setAdding] = useState(false);+ const [date, setDate] = useState("");+ const [name, setName] = useState("");++ const year = today.slice(0, 4);+ const list = holidays.filter((h) => h.date.startsWith(year));+ const next = list.find((h) => h.date >= today);++ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-4 p-5 sm:max-w-[440px]">+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">National holidays {year}</DialogTitle>+ <DialogDescription className="t-14">+ {list.length} public holidays · they’re never deducted from your allowance.+ </DialogDescription>+ </DialogHeader>+ <ScrollArea className="-mx-2 max-h-[360px]">+ <ul className="grid gap-0.5 px-2">+ {list.map((h) => {+ const past = h.date < today;+ return (+ <li key={h.id} className="group flex items-center gap-1">+ <button+ type="button"+ onClick={() => {+ useCalendarStore.getState().setDate(h.date);+ onClose();+ router.push("/time-off");+ }}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors duration-150 hover-fine:bg-hover",+ past && "opacity-55",+ )}+ >+ <span className="flex w-11 shrink-0 flex-col items-center gap-1 rounded-md bg-[var(--event-purple-bg)] py-1.5 text-[var(--event-purple-fg)]">+ <span className="text-[10px] leading-none tracking-wide uppercase">{MONTHS[Number(h.date.slice(5, 7)) - 1].slice(0, 3)}</span>+ <span className="t-16">{Number(h.date.slice(8))}</span>+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-1.5">+ <span className="t-14 truncate text-fg">{h.name}</span>+ <span className="t-12 text-fg-2">{formatWeekday(h.date)}</span>+ </span>+ {next?.id === h.id && (+ <span className="t-12 shrink-0 rounded-md bg-brand-tint px-1.5 py-1 text-brand">Next up</span>+ )}+ </button>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={`Remove ${h.name}`}+ className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ onClick={() => removeHoliday(h.id)}+ >+ <Trash2Icon />+ </Button>+ </li>+ );+ })}+ </ul>+ </ScrollArea>+ {adding ? (+ <form+ className="grid grid-cols-[1fr_1.3fr_auto] gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ if (!date || !name.trim()) return;+ addHoliday(date, name.trim());+ setDate("");+ setName("");+ setAdding(false);+ }}+ >+ <Input type="date" required value={date} onChange={(e) => setDate(e.target.value)} aria-label="Holiday date" />+ <Input required placeholder="Holiday name" value={name} onChange={(e) => setName(e.target.value)} autoFocus />+ <Button type="submit" variant="brand">+ Add+ </Button>+ </form>+ ) : (+ <DialogFooter className="-mx-5 -mb-5 bg-app px-5 py-3">+ <Button onClick={() => setAdding(true)}>+ <PlusIcon /> Add holiday+ </Button>+ <Button variant="brand" onClick={onClose}>+ Done+ </Button>+ </DialogFooter>+ )}+ </DialogContent>+ </Dialog>+ );+}++export function PolicyDialog({ open, onClose }: BaseProps) {+ const today = useToday();+ const requests = useAppStore((s) => s.requests);+ const settings = useAppStore((s) => s.settings);+ const holidays = useAppStore((s) => s.holidays);+ const stats = computeLeaveStats({ requests, settings, holidays }, today);+ const total = stats.contract + stats.carryover;+ const used = total - stats.available - stats.pendingDays;++ const sections = [+ {+ title: "Annual allowance",+ body: `Your contract includes ${stats.contract} days of paid time off per calendar year, plus ${stats.carryover} carryover days from last year.`,+ },+ {+ title: "How days are counted",+ body: "Only working days count. Weekends and national holidays inside a request are skipped automatically; partial days are counted in hours (8h = 1 day).",+ },+ {+ title: "Approval",+ body: "Requests go to your manager. Pending requests are held against your balance until they’re approved or declined.",+ },+ {+ title: "Sick leave",+ body: "Sick leave longer than one day needs a medical certificate uploaded in Documents within 3 working days.",+ },+ ];++ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-5 p-5 sm:max-w-[480px]">+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">Time off policy</DialogTitle>+ <DialogDescription className="t-14">How your allowance works this year.</DialogDescription>+ </DialogHeader>+ <div className="grid gap-2">+ <div className="flex h-2 overflow-hidden rounded-full bg-hairline">+ <span className="bg-success transition-[width] duration-500 ease-(--ease-out)" style={{ width: `${(used / total) * 100}%` }} />+ <span className="bg-warning" style={{ width: `${(stats.pendingDays / total) * 100}%` }} />+ </div>+ <div className="t-12 flex gap-4 text-fg-2">+ <span className="flex items-center gap-1.5">+ <span className="size-2 rounded-full bg-success" /> {formatDays(used)} used+ </span>+ <span className="flex items-center gap-1.5">+ <span className="size-2 rounded-full bg-warning" /> {formatDays(stats.pendingDays)} pending+ </span>+ <span className="flex items-center gap-1.5">+ <span className="size-2 rounded-full bg-hairline" /> {formatDays(stats.available)} available+ </span>+ </div>+ </div>+ <div className="grid gap-4">+ {sections.map((s) => (+ <section key={s.title} className="grid gap-1.5">+ <h3 className="t-14 text-fg">{s.title}</h3>+ <p className="t-14 leading-[1.45] text-fg-2">{s.body}</p>+ </section>+ ))}+ </div>+ <DialogFooter className="-mx-5 -mb-5 bg-app px-5 py-3">+ <Button variant="brand" onClick={onClose}>+ Got it+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++export function ShortcutsDialog({ open, onClose }: BaseProps) {+ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-4 p-5 sm:max-w-[400px]">+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">Keyboard shortcuts</DialogTitle>+ <DialogDescription className="t-14">Move around without leaving the keyboard.</DialogDescription>+ </DialogHeader>+ <ul className="grid gap-1">+ {SHORTCUTS.map((s) => (+ <li key={s.label} className="flex h-8 items-center justify-between">+ <span className="t-14 text-fg">{s.label}</span>+ <span className="flex gap-1">+ {s.keys.map((k) => (+ <kbd+ key={k}+ className="flex h-6 min-w-6 items-center justify-center rounded-md border border-control bg-app px-1.5 font-mono text-[12px] text-fg-2"+ >+ {k}+ </kbd>+ ))}+ </span>+ </li>+ ))}+ </ul>+ </DialogContent>+ </Dialog>+ );+}+diff --git a/src/components/dialogs/request-details-dialog.tsx b/src/components/dialogs/request-details-dialog.tsxnew file mode 100644index 0000000..cfa63d2--- /dev/null+++ b/src/components/dialogs/request-details-dialog.tsx@@ -0,0 +1,135 @@+"use client";++import { useRouter } from "next/navigation";+import { useState } from "react";+import { CalendarSearchIcon, CheckIcon, PencilIcon, Trash2Icon, XIcon } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Separator } from "@/components/ui/separator";+import { StatusBadge } from "@/components/time-off/status-badge";+import { formatLong, formatTimeRange, relativeTime } from "@/lib/dates";+import { useNow, useToday } from "@/hooks/use-today";+import { useAppStore } from "@/stores/app-store";+import { useCalendarStore } from "@/stores/calendar-store";+import { openOverlay } from "@/stores/overlay-store";++export function RequestDetailsDialog({ open, onClose, requestId }: { open: boolean; onClose: () => void; requestId?: string }) {+ const router = useRouter();+ const request = useAppStore((s) => s.requests.find((r) => r.id === requestId));+ const timeFormat = useAppStore((s) => s.settings.timeFormat);+ const setStatus = useAppStore((s) => s.setRequestStatus);+ const deleteRequest = useAppStore((s) => s.deleteRequest);+ const today = useToday();+ const now = useNow();+ const [confirming, setConfirming] = useState(false);++ if (!request) return null;+ const canCancel = request.status === "pending" || (request.status === "approved" && request.from >= today);++ const rows: [string, React.ReactNode][] = [+ ["Leave type", request.type],+ ["Duration", request.duration],+ ["From", formatLong(request.from)],+ ["To", formatLong(request.to)],+ ...(!request.allDay && request.start !== undefined && request.end !== undefined+ ? ([["Hours", formatTimeRange(request.start, request.end, timeFormat)]] as [string, React.ReactNode][])+ : []),+ ["Submitted", now ? relativeTime(request.submittedAt, now) : formatLong(request.submittedAt.slice(0, 10))],+ ];++ return (+ <>+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-5 p-5 sm:max-w-[440px]">+ <DialogHeader className="gap-3">+ <StatusBadge status={request.status} className="self-start" />+ <DialogTitle className="t-16 leading-[1.3]">{request.notes}</DialogTitle>+ <DialogDescription className="sr-only">Leave request details</DialogDescription>+ </DialogHeader>+ <dl className="grid gap-3">+ {rows.map(([k, v]) => (+ <div key={k} className="flex items-center justify-between gap-4">+ <dt className="t-14 text-fg-2">{k}</dt>+ <dd className="t-14 text-right text-table">{v}</dd>+ </div>+ ))}+ </dl>+ <Separator />+ <div className="flex flex-wrap gap-2">+ <Button+ onClick={() => {+ useCalendarStore.getState().setDate(request.from);+ onClose();+ router.push("/time-off");+ }}+ >+ <CalendarSearchIcon /> Show in calendar+ </Button>+ {request.status === "pending" && (+ <Button onClick={() => openOverlay({ kind: "request", requestId: request.id })}>+ <PencilIcon /> Edit+ </Button>+ )}+ {canCancel && (+ <Button+ onClick={() => {+ setStatus(request.id, "cancelled");+ onClose();+ }}+ >+ <XIcon /> Cancel request+ </Button>+ )}+ <Button variant="destructive" className="ml-auto" onClick={() => setConfirming(true)}>+ <Trash2Icon /> Delete+ </Button>+ </div>+ {request.status === "pending" && (+ <div className="-mx-5 -mb-5 flex items-center gap-2 border-t border-hairline bg-app px-5 py-3">+ <span className="t-12 flex-1 text-fg-2">Manager preview — simulate a decision</span>+ <Button size="sm" onClick={() => setStatus(request.id, "declined")}>+ <XIcon className="text-danger" /> Decline+ </Button>+ <Button size="sm" variant="brand" onClick={() => setStatus(request.id, "approved")}>+ <CheckIcon /> Approve+ </Button>+ </div>+ )}+ </DialogContent>+ </Dialog>++ <AlertDialog open={confirming} onOpenChange={setConfirming}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle className="t-16">Delete this request?</AlertDialogTitle>+ <AlertDialogDescription className="t-14 leading-[1.4]">+ It will be removed from your history and its calendar events deleted. You can undo right after.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ deleteRequest(request.id);+ onClose();+ }}+ >+ Delete request+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/src/components/dialogs/request-dialog.tsx b/src/components/dialogs/request-dialog.tsxnew file mode 100644index 0000000..17bae5e--- /dev/null+++ b/src/components/dialogs/request-dialog.tsx@@ -0,0 +1,219 @@+"use client";++import { useMemo, useState } from "react";+import { AlertTriangleIcon } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { formatLong, parseTime, timeInputValue } from "@/lib/dates";+import { computeLeaveStats, formatDays, LEAVE_COLORS, LEAVE_TYPES } from "@/lib/leave";+import type { LeaveRequest, LeaveType } from "@/lib/types";+import { useToday } from "@/hooks/use-today";+import { useAppStore, type RequestInput } from "@/stores/app-store";+import { useCalendarStore } from "@/stores/calendar-store";+import { Field } from "./field";++type Props = { open: boolean; session: number; onClose: () => void; requestId?: string; from?: string };++export function RequestDialog({ open, session, onClose, requestId, from }: Props) {+ return (+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <DialogContent className="gap-5 p-5 sm:max-w-[460px]">+ {/* Keyed by open-session so the form starts fresh every time */}+ <RequestForm key={session} requestId={requestId} from={from} onDone={onClose} />+ </DialogContent>+ </Dialog>+ );+}++function initialInput(existing: LeaveRequest | undefined, from: string): RequestInput {+ if (existing) {+ return {+ type: existing.type,+ from: existing.from,+ to: existing.to,+ allDay: existing.allDay,+ start: existing.start ?? 540,+ end: existing.end ?? 1020,+ notes: existing.notes,+ };+ }+ return { type: "Time off", from, to: from, allDay: true, start: 540, end: 780, notes: "" };+}++function RequestForm({ requestId, from, onDone }: { requestId?: string; from?: string; onDone: () => void }) {+ const today = useToday();+ const calendarDate = useCalendarStore((s) => s.date);+ const requests = useAppStore((s) => s.requests);+ const settings = useAppStore((s) => s.settings);+ const holidays = useAppStore((s) => s.holidays);+ const measure = useAppStore((s) => s.measureRequest);+ const submit = useAppStore((s) => s.submitRequest);+ const existing = requests.find((r) => r.id === requestId);++ const [form, setForm] = useState<RequestInput>(() =>+ initialInput(existing, from ?? (calendarDate >= today ? calendarDate : today)),+ );+ const set = <K extends keyof RequestInput>(k: K, v: RequestInput[K]) => setForm((f) => ({ ...f, [k]: v }));++ const stats = useMemo(+ () => computeLeaveStats({ requests: requests.filter((r) => r.id !== requestId), settings, holidays }, today),+ [requests, requestId, settings, holidays, today],+ );+ const measured = measure(form);++ const error =+ form.allDay && form.to < form.from+ ? "End date must be on or after the start date."+ : !form.allDay && form.end <= form.start+ ? "End time must be after the start time."+ : form.allDay && measured.days === 0+ ? "These dates fall on weekends or holidays — nothing to request."+ : null;+ const remaining = stats.available - measured.days;++ return (+ <form+ className="contents"+ onSubmit={(e) => {+ e.preventDefault();+ if (error) return;+ submit(form, requestId);+ onDone();+ }}+ >+ <DialogHeader className="gap-1.5">+ <DialogTitle className="t-16">{existing ? "Edit request" : "Request time-off"}</DialogTitle>+ <DialogDescription className="t-14">+ {existing ? "Changes are sent back to your manager for approval." : "Your manager is notified as soon as you submit."}+ </DialogDescription>+ </DialogHeader>++ <div className="grid gap-4">+ <Field label="Leave type" htmlFor="rq-type">+ <Select value={form.type} onValueChange={(v) => set("type", v as LeaveType)}>+ <SelectTrigger id="rq-type" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {LEAVE_TYPES.map((t) => (+ <SelectItem key={t} value={t}>+ <span className="size-2 rounded-full" style={{ background: `var(--event-${LEAVE_COLORS[t]}-fg)` }} />+ {t}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>++ <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">Full days</span>+ <span className="t-12 text-fg-2">Turn off to request a few hours on one day</span>+ </span>+ <Switch checked={form.allDay} onCheckedChange={(v) => set("allDay", v)} />+ </label>++ {form.allDay ? (+ <div className="grid grid-cols-2 gap-3">+ <Field label="From" htmlFor="rq-from">+ <Input+ id="rq-from"+ type="date"+ required+ value={form.from}+ onChange={(e) => {+ const v = e.target.value;+ setForm((f) => ({ ...f, from: v, to: f.to < v ? v : f.to }));+ }}+ />+ </Field>+ <Field label="To" htmlFor="rq-to">+ <Input id="rq-to" type="date" required min={form.from} value={form.to} onChange={(e) => set("to", e.target.value)} />+ </Field>+ </div>+ ) : (+ <div className="grid grid-cols-[1.4fr_1fr_1fr] gap-3">+ <Field label="Date" htmlFor="rq-date">+ <Input id="rq-date" type="date" required value={form.from} onChange={(e) => set("from", e.target.value)} />+ </Field>+ <Field label="From" htmlFor="rq-start">+ <Input+ id="rq-start"+ type="time"+ step={900}+ value={timeInputValue(form.start)}+ onChange={(e) => set("start", parseTime(e.target.value))}+ />+ </Field>+ <Field label="To" htmlFor="rq-end">+ <Input+ id="rq-end"+ type="time"+ step={900}+ value={timeInputValue(form.end)}+ onChange={(e) => set("end", parseTime(e.target.value))}+ />+ </Field>+ </div>+ )}++ <Field label="Notes" htmlFor="rq-notes">+ <Textarea+ id="rq-notes"+ rows={3}+ placeholder="Add context for your manager (optional)"+ value={form.notes}+ onChange={(e) => set("notes", e.target.value)}+ />+ </Field>++ <div className="grid grid-cols-2 gap-px overflow-hidden rounded-lg border border-hairline bg-hairline">+ <div className="grid gap-2 bg-app px-3 py-2.5">+ <span className="t-12 text-fg-2">Duration</span>+ <span className="t-14 text-fg">{error ? "—" : measured.label}</span>+ </div>+ <div className="grid gap-2 bg-app px-3 py-2.5">+ <span className="t-12 text-fg-2">Balance after request</span>+ <span className={remaining < 0 ? "t-14 text-danger" : "t-14 text-fg"}>+ {formatDays(Math.max(remaining, -99))} {Math.abs(remaining) === 1 ? "day" : "days"}+ </span>+ </div>+ </div>++ {error ? (+ <p className="t-12 flex items-center gap-1.5 text-danger" role="alert">+ <AlertTriangleIcon className="size-3.5" /> {error}+ </p>+ ) : remaining < 0 ? (+ <p className="t-12 flex items-center gap-1.5 text-warning">+ <AlertTriangleIcon className="size-3.5" /> This exceeds your balance — it may be unpaid leave.+ </p>+ ) : form.allDay && form.from !== form.to ? (+ <p className="t-12 text-fg-2">+ {formatLong(form.from)} – {formatLong(form.to)} · weekends and public holidays aren’t counted.+ </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}>+ {existing ? "Save changes" : "Submit request"}+ </Button>+ </DialogFooter>+ </form>+ );+}diff --git a/src/components/time-off/status-badge.tsx b/src/components/time-off/status-badge.tsxnew file mode 100644index 0000000..f328f3b--- /dev/null+++ b/src/components/time-off/status-badge.tsx@@ -0,0 +1,31 @@+import { BanIcon, Clock3Icon } from "lucide-react";+import { Icon } from "@/components/icon";+import { cn } from "@/lib/utils";+import type { LeaveStatus } from "@/lib/types";++const STYLES: Record<LeaveStatus, { label: string; tone: string }> = {+ approved: { label: "Approved", tone: "success" },+ declined: { label: "Declined", tone: "danger" },+ pending: { label: "Pending", tone: "warning" },+ cancelled: { label: "Cancelled", tone: "neutral" },+};++export function StatusBadge({ status, className }: { status: LeaveStatus; className?: string }) {+ const { label, tone } = STYLES[status];+ return (+ <span+ className={cn("inline-flex h-[22px] shrink-0 items-center gap-1 rounded-[6px] border pr-1.5 pl-1", className)}+ style={{+ background: `var(--status-${tone}-tint)`,+ borderColor: `var(--status-${tone}-border)`,+ color: `var(--status-${tone})`,+ }}+ >+ {status === "approved" && <Icon name="status-approved" className="text-success" />}+ {status === "declined" && <Icon name="status-declined" className="rotate-180 text-danger" />}+ {status === "pending" && <Clock3Icon className="size-3.5" strokeWidth={2.25} />}+ {status === "cancelled" && <BanIcon className="size-3.5" strokeWidth={2.25} />}+ <span className="salt text-[12px] leading-none tracking-[-0.24px] whitespace-nowrap">{label}</span>+ </span>+ );+}