Skip to content

Email for professionals and teams

[fix] calendar drag item performance

Hieu Nguyen (Jack)fbce7950b3e6
diff --git a/src/app/(calendar)/calendar-mobile-upcoming.tsx b/src/app/(calendar)/calendar-mobile-upcoming.tsx
new file mode 100644
index 0000000..619d094
--- /dev/null
+++ b/src/app/(calendar)/calendar-mobile-upcoming.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useSidebar } from "@/components/sidebar-state";
+import { UpcomingSidebar } from "./upcoming-sidebar";
+
+// Phone menu for the calendar section: the upcoming events list, as the desktop left column shows.
+// Stays mounted while the menu is closed so the loaded list is still there next time it opens;
+// opening refreshes it in the background.
+export function CalendarMobileUpcoming() {
+ const { mobile, mobileOpen, toggle } = useSidebar();
+ const router = useRouter();
+ if (!mobile) return null;
+ return (
+ <UpcomingSidebar drawer refreshKey={mobileOpen} onSelect={(event) => {
+ toggle();
+ router.push(`/calendar?event=${encodeURIComponent(event.id)}`);
+ }} />
+ );
+}
diff --git a/src/app/(calendar)/calendar/day-events-types.d.ts b/src/app/(calendar)/calendar/day-events-types.d.ts
new file mode 100644
index 0000000..40c45f2
--- /dev/null
+++ b/src/app/(calendar)/calendar/day-events-types.d.ts
@@ -0,0 +1,17 @@
+import type { DragEvent, PointerEvent as ReactPointerEvent } from "react";
+import type { CalendarEvent, EventResizeEdge } from "./types";
+
+export type DayEventsProps = {
+ day: Date;
+ events: CalendarEvent[];
+ currentTime: number;
+ busy: boolean;
+ activeEventId: string | null;
+ onEdit: (event: CalendarEvent) => void;
+ onDragStart: (dragEvent: DragEvent<HTMLButtonElement>, event: CalendarEvent) => void;
+ onDragEnd: () => void;
+ onResizeStart: (pointerEvent: ReactPointerEvent<HTMLButtonElement>, event: CalendarEvent, day: Date, edge: EventResizeEdge) => void;
+ onResizeMove: (pointerEvent: ReactPointerEvent<HTMLButtonElement>) => void;
+ onResizeEnd: (pointerEvent: ReactPointerEvent<HTMLButtonElement>) => void;
+ onResizeCancel: () => void;
+};
diff --git a/src/app/(calendar)/calendar/day-events.tsx b/src/app/(calendar)/calendar/day-events.tsx
new file mode 100644
index 0000000..89ff93b
--- /dev/null
+++ b/src/app/(calendar)/calendar/day-events.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { Fragment, memo, useMemo } from "react";
+import type { DragEvent, PointerEvent as ReactPointerEvent } from "react";
+import clsx from "clsx";
+import { normalizeCalendarColor } from "@/lib/calendar/colors";
+import { addDays, dateKey, EVENT_COLOR_CLASSES, eventPosition, formatEventRange, PAST_EVENT_COLOR_CLASSES } from "./utils";
+import type { CalendarEvent, EventResizeEdge } from "./types";
+import type { DayEventsProps } from "./day-events-types";
+
+// Memoized so pointer-move / drag-over preview updates in the page do not
+// recompute positions (timezone math) and re-render every event block.
+function DayEventsImpl({ day, events, currentTime, busy, activeEventId, onEdit, onDragStart, onDragEnd, onResizeStart, onResizeMove, onResizeEnd, onResizeCancel }: DayEventsProps) {
+ const nextDay = useMemo(() => addDays(day, 1), [day]);
+ const items = useMemo(() => events.flatMap((event) => {
+ if (!(new Date(event.startsAt) < nextDay && new Date(event.endsAt) > day)) return [];
+ const position = eventPosition(event, day);
+ if (!position) return [];
+ return [{
+ event,
+ position,
+ color: normalizeCalendarColor(event.color),
+ range: formatEventRange(event),
+ canResizeStart: dateKey(new Date(event.startsAt)) === dateKey(day),
+ canResizeEnd: new Date(event.endsAt).getTime() <= nextDay.getTime(),
+ }];
+ }), [events, day, nextDay]);
+
+ return (
+ <>
+ {items.map(({ event, position, color, range, canResizeStart, canResizeEnd }) => {
+ const isPastEvent = new Date(event.endsAt).getTime() <= currentTime;
+ const edges = (["start", "end"] as const).filter((edge) => edge === "start" ? canResizeStart : canResizeEnd);
+ // Keep the grab zone inside the event so it never steals clicks from neighbours.
+ const handleHeight = Math.max(4, Math.min(10, position.height / 3));
+ return (
+ <Fragment key={event.id}>
+ <button type="button" draggable={!busy} onClick={() => onEdit(event)}
+ onDragStart={(dragEvent: DragEvent<HTMLButtonElement>) => onDragStart(dragEvent, event)}
+ onDragEnd={onDragEnd}
+ title={`${event.title} · ${range}`}
+ className={`absolute left-1 right-1 z-10 flex cursor-move flex-col items-start justify-start overflow-hidden rounded-lg pr-2 pl-4 text-left hover:brightness-95 ${isPastEvent ? PAST_EVENT_COLOR_CLASSES[color] : EVENT_COLOR_CLASSES[color]} ${position.height >= 20 ? "py-1.5" : "py-0"} ${activeEventId === event.id ? "opacity-40" : ""}`}
+ style={{ top: position.top, height: position.height }}>
+ <span className="absolute top-1 left-1 block h-[calc(100%-8px)] w-1 rounded-xl bg-current" />
+ {position.height >= 15 && <span className="block w-full truncate text-[12px] font-semibold leading-4">{event.title}</span>}
+ {position.height >= 34 && <span className="block w-full truncate text-[11px] leading-4 opacity-70">{range}</span>}
+ </button>
+ {edges.map((edge: EventResizeEdge) => (
+ <button key={edge} type="button" draggable={false}
+ aria-label={`Resize ${edge} of ${event.title}`}
+ onPointerDown={(pointerEvent: ReactPointerEvent<HTMLButtonElement>) => onResizeStart(pointerEvent, event, day, edge)}
+ onPointerMove={onResizeMove}
+ onPointerUp={onResizeEnd}
+ onPointerCancel={onResizeCancel}
+ onClick={(clickEvent) => clickEvent.stopPropagation()}
+ className={clsx("absolute left-1 right-1 z-20 cursor-ns-resize touch-none bg-transparent focus-visible:outline-2 focus-visible:outline-blue-500")}
+ style={{ height: handleHeight, top: edge === "start" ? position.top : position.top + position.height - handleHeight }} />
+ ))}
+ </Fragment>
+ );
+ })}
+ </>
+ );
+}
+
+export const DayEvents = memo(DayEventsImpl);
+export type { CalendarEvent };
diff --git a/src/app/(calendar)/calendar/page.tsx b/src/app/(calendar)/calendar/page.tsx
index edcd3c4..8125a79 100644
--- a/src/app/(calendar)/calendar/page.tsx
+++ b/src/app/(calendar)/calendar/page.tsx
@@ -1,8 +1,8 @@
"use client";
-import { Fragment, useEffect, useMemo, useRef, useState } from "react";
-import Link from "next/link";
-import type { PointerEvent as ReactPointerEvent } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import type { DragEvent, PointerEvent as ReactPointerEvent } from "react";
import { createPortal } from "react-dom";
import toast, { Toaster } from "react-hot-toast";
import { AlignLeft, CalendarPlus2, Check, ChevronDown, ChevronLeft, ChevronRight, Clock3, MapPin, MoreVertical, Palette, Plus, Repeat2, Trash2, UsersRound, X } from "lucide-react";
@@ -21,6 +21,7 @@ import type { CalendarRepeat } from "@/lib/calendar/types";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useSidebar } from "@/components/sidebar-state";
import { UpcomingSidebar } from "../upcoming-sidebar";
+import { DayEvents } from "./day-events";
import type { CalendarEvent, CalendarView, EventDragPreview, EventResizeEdge, EventResizeSession } from "./types";
import {
addDays, addMonths, calendarAnchorDay, CALENDAR_END_HOUR, CALENDAR_HOUR_HEIGHT, CALENDAR_START_HOUR,
@@ -42,6 +43,8 @@ export default function CalendarPage() {
const [monthPickerOpen, setMonthPickerOpen] = useState(false);
const [pickerMonth, setPickerMonth] = useState(() => new Date());
const monthPickerRef = useRef<HTMLDivElement | null>(null);
+ const monthPickerPopupRef = useRef<HTMLDivElement | null>(null);
+ const [monthPickerPos, setMonthPickerPos] = useState<{ top: number; left: number } | null>(null);
const openedEventFromUrl = useRef<string | null>(null);
const [headerTarget, setHeaderTarget] = useState<HTMLElement | null>(null);
const [draggedEvent, setDraggedEvent] = useState<CalendarEvent | null>(null);
@@ -63,6 +66,8 @@ export default function CalendarPage() {
const [description, setDescription] = useState("");
const [editing, setEditing] = useState<CalendarEvent | null>(null);
const [pendingAction, setPendingAction] = useState<"save" | string | null>(null);
+ const router = useRouter();
+ const eventFromUrl = useSearchParams().get("event");
const { selectedMailbox } = useSelectedMailbox();
const { minimal: sidebarMinimal, mobile } = useSidebar();
const minimal = sidebarMinimal || mobile;
@@ -99,7 +104,8 @@ export default function CalendarPage() {
useEffect(() => {
if (!monthPickerOpen) return;
const closeOnOutsidePointer = (event: PointerEvent) => {
- if (!monthPickerRef.current?.contains(event.target as Node)) setMonthPickerOpen(false);
+ const target = event.target as Node;
+ if (!monthPickerRef.current?.contains(target) && !monthPickerPopupRef.current?.contains(target)) setMonthPickerOpen(false);
};
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") setMonthPickerOpen(false);
@@ -129,13 +135,15 @@ export default function CalendarPage() {
}, [today, visibleDate, weekStart, eventsVersion]);
useEffect(() => {
- const eventFromUrl = new URLSearchParams(window.location.search).get("event");
- if (!eventFromUrl || openedEventFromUrl.current === eventFromUrl) return;
+ if (!eventFromUrl) { openedEventFromUrl.current = null; return; }
+ if (openedEventFromUrl.current === eventFromUrl) return;
const event = events.find((item) => item.id === eventFromUrl);
if (!event) return;
openedEventFromUrl.current = eventFromUrl;
editEvent(event);
- }, [events]);
+ // Drop the param so picking the same event again re-opens it.
+ router.replace("/calendar");
+ }, [events, eventFromUrl]);
function openNewEvent(day = visibleDate, startAt?: Date) {
const start = startAt ? new Date(startAt) : defaultCalendarStart(day);
@@ -245,6 +253,12 @@ export default function CalendarPage() {
return;
}
setPendingAction(event.id);
+ // Non-recurring events move in place right away; the refetch below confirms.
+ const previousEvents = event.repeat === "none" ? events : null;
+ if (previousEvents) {
+ setEvents((current) => current.map((item) => item.id === event.id ? { ...item, startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString() } : item));
+ }
+ let saved = false;
try {
const movingToPast = event.repeat !== "none" && startsAt.getTime() < Date.now();
const effectiveFrom = event.repeat !== "none" && !movingToPast ? new Date() : null;
@@ -283,10 +297,12 @@ export default function CalendarPage() {
toast.error("Could not update the event time. Please try again.");
return;
}
+ saved = true;
setEventsVersion((version) => version + 1);
} catch {
toast.error("Could not update the event time. Please try again.");
} finally {
+ if (previousEvents && !saved) setEvents(previousEvents);
setDraggedEvent(null);
setResizingEvent(null);
setDragPreview(null);
@@ -318,12 +334,10 @@ export default function CalendarPage() {
if (Math.abs(pointerEvent.clientY - session.pointerY) < 3) return;
session.moved = true;
const times = resizeEventTimes(session.event, session.day, session.edge, pointerEvent.clientY - session.columnTop);
- setDragPreview({
- eventId: session.event.id,
- day: session.day,
- startsAt: times.startsAt,
- endsAt: times.endsAt,
- });
+ // Times snap to 15 minutes, so most pointer moves change nothing.
+ setDragPreview((current) => current && current.startsAt.getTime() === times.startsAt.getTime() && current.endsAt.getTime() === times.endsAt.getTime()
+ ? current
+ : { eventId: session.event.id, day: session.day, startsAt: times.startsAt, endsAt: times.endsAt });
}
function finishResize(pointerEvent: ReactPointerEvent<HTMLButtonElement>) {
@@ -347,6 +361,23 @@ export default function CalendarPage() {
setDragPreview(null);
}
+ const handlers = useRef({ editEvent, startResize, updateResize, finishResize, cancelResize });
+ handlers.current = { editEvent, startResize, updateResize, finishResize, cancelResize };
+ const onEditEvent = useCallback((event: CalendarEvent) => handlers.current.editEvent(event), []);
+ const onResizeStart = useCallback((pointerEvent: ReactPointerEvent<HTMLButtonElement>, event: CalendarEvent, day: Date, edge: EventResizeEdge) => handlers.current.startResize(pointerEvent, event, day, edge), []);
+ const onResizeMove = useCallback((pointerEvent: ReactPointerEvent<HTMLButtonElement>) => handlers.current.updateResize(pointerEvent), []);
+ const onResizeEnd = useCallback((pointerEvent: ReactPointerEvent<HTMLButtonElement>) => handlers.current.finishResize(pointerEvent), []);
+ const onResizeCancel = useCallback(() => handlers.current.cancelResize(), []);
+ const onEventDragStart = useCallback((dragEvent: DragEvent<HTMLButtonElement>, event: CalendarEvent) => {
+ dragOffsetPixels.current = dragEvent.clientY - dragEvent.currentTarget.getBoundingClientRect().top;
+ dragEvent.dataTransfer.setData("text/plain", event.id);
+ dragEvent.dataTransfer.effectAllowed = "move";
+ setDraggedEvent(event);
+ }, []);
+ const onEventDragEnd = useCallback(() => { setDraggedEvent(null); setDragPreview(null); }, []);
+ const busy = pendingAction !== null;
+ const activeEventId = draggedEvent?.id ?? resizingEvent?.id ?? null;
+
return (
<div className={clsx("flex h-full min-h-0 flex-col bg-[#f6f8fc] pl-3 max-md:pl-0 lg:flex-row transition-[gap] duration-200 ease-in-out motion-reduce:transition-none", minimal ? "gap-0" : "gap-3")}>
<Toaster position="bottom-right" />
@@ -355,15 +386,17 @@ export default function CalendarPage() {
<div className="flex min-w-0 flex-1 items-center justify-between gap-3 ">
<div className="flex shrink-0 items-center gap-2">
<div ref={monthPickerRef} className="relative shrink-0">
- <button type="button" onClick={() => {
+ <button type="button" onClick={(event) => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ setMonthPickerPos({ top: rect.bottom + 12, left: Math.max(12, Math.min(rect.left, window.innerWidth - 460)) });
setPickerMonth(startOfMonth(visibleDate));
setMonthPickerOpen((open) => !open);
}} className="flex items-center gap-2 whitespace-nowrap text-lg font-semibold text-neutral-900 max-md:text-base max-md:font-medium" aria-haspopup="dialog" aria-expanded={monthPickerOpen}>
{formatUserDate(visibleDate, { month: "long", year: "numeric" })}
<ChevronDown className="h-5 w-5 text-neutral-500" />
</button>
- {monthPickerOpen && (
- <div role="dialog" aria-label="Choose a calendar date" className="absolute left-0 top-full z-50 mt-3 w-[448px] max-w-[calc(100vw-24px)] rounded-2xl bg-[#f7f9fc] p-5 shadow-xl ring-1 ring-neutral-200/70">
+ {monthPickerOpen && monthPickerPos && createPortal(
+ <div ref={monthPickerPopupRef} role="dialog" aria-label="Choose a calendar date" style={monthPickerPos} className="fixed z-50 w-[448px] max-w-[calc(100vw-24px)] rounded-2xl bg-[#f7f9fc] p-5 shadow-xl ring-1 ring-neutral-200/70">
<div className="mb-4 flex items-center justify-between gap-3">
<h2 className="text-xl font-semibold text-neutral-900">
{formatUserDate(pickerMonth, { month: "long", year: "numeric" })}
@@ -395,7 +428,8 @@ export default function CalendarPage() {
);
})}
</div>
- </div>
+ </div>,
+ document.body,
)}
</div>
</div>
@@ -466,39 +500,9 @@ export default function CalendarPage() {
}}
style={{ backgroundImage: "linear-gradient(to bottom, transparent calc(100% - 1px), var(--color-neutral-100) calc(100% - 1px))", backgroundSize: `100% ${CALENDAR_HOUR_HEIGHT}px` }}>
<button type="button" aria-label={`Add event on ${formatUserDate(day, { dateStyle: "short" })}`} onClick={(event) => openNewEvent(day, dropStartForPosition(day, event.nativeEvent.offsetY))} className="absolute inset-0 z-0 cursor-crosshair" />
- {events.filter((event) => new Date(event.startsAt) < addDays(day, 1) && new Date(event.endsAt) > day).map((event) => {
- const position = eventPosition(event, day);
- if (!position) return null;
- const eventColor = normalizeCalendarColor(event.color);
- const isPastEvent = new Date(event.endsAt).getTime() <= currentTime;
- const canResizeStart = dateKey(new Date(event.startsAt)) === dateKey(day);
- const canResizeEnd = new Date(event.endsAt).getTime() <= addDays(day, 1).getTime();
- return (
- <Fragment key={event.id}>
- <button type="button" draggable={pendingAction === null} onClick={() => editEvent(event)}
- onDragStart={(dragEvent) => { dragOffsetPixels.current = dragEvent.clientY - dragEvent.currentTarget.getBoundingClientRect().top; dragEvent.dataTransfer.setData("text/plain", event.id); dragEvent.dataTransfer.effectAllowed = "move"; setDraggedEvent(event); }}
- onDragEnd={() => { setDraggedEvent(null); setDragPreview(null); }}
- title={`${event.title} · ${formatEventRange(event)}`}
- className={`absolute left-1 right-1 z-10 flex cursor-move flex-col items-start justify-start overflow-hidden rounded-lg pr-2 pl-4 text-left hover:brightness-95 ${isPastEvent ? PAST_EVENT_COLOR_CLASSES[eventColor] : EVENT_COLOR_CLASSES[eventColor]} ${position.height >= 20 ? "py-1.5" : "py-0"} ${draggedEvent?.id === event.id || resizingEvent?.id === event.id ? "opacity-40" : ""}`}
- style={{ top: position.top, height: position.height }}>
- <span className="absolute top-1 left-1 block h-[calc(100%-8px)] w-1 rounded-xl bg-current" />
- {position.height >= 15 && <span className="block w-full truncate text-[12px] font-semibold leading-4">{event.title}</span>}
- {position.height >= 34 && <span className="block w-full truncate text-[11px] leading-4 opacity-70">{formatEventRange(event)}</span>}
- </button>
- {(["start", "end"] as const).filter((edge) => edge === "start" ? canResizeStart : canResizeEnd).map((edge) => (
- <button key={edge} type="button" draggable={false}
- aria-label={`Resize ${edge} of ${event.title}`}
- onPointerDown={(pointerEvent) => startResize(pointerEvent, event, day, edge)}
- onPointerMove={updateResize}
- onPointerUp={finishResize}
- onPointerCancel={cancelResize}
- onClick={(clickEvent) => clickEvent.stopPropagation()}
- className={clsx(edge === "start" ? "cursor-n-resize" : "cursor-s-resize", "absolute left-1 right-1 z-20 h-2 touch-none bg-transparent focus-visible:outline-2 focus-visible:outline-blue-500")}
- style={{ top: edge === "start" ? position.top - 4 : position.top + position.height - 4 }} />
- ))}
- </Fragment>
- );
- })}
+ <DayEvents day={day} events={events} currentTime={currentTime} busy={busy} activeEventId={activeEventId}
+ onEdit={onEditEvent} onDragStart={onEventDragStart} onDragEnd={onEventDragEnd}
+ onResizeStart={onResizeStart} onResizeMove={onResizeMove} onResizeEnd={onResizeEnd} onResizeCancel={onResizeCancel} />
{dragPreview && previewEvent && previewPosition && dateKey(dragPreview.day) === dateKey(day) && (
<div className={`pointer-events-none absolute left-1 right-1 z-20 rounded-lg border-2 border-dashed border-white ${new Date(previewEvent.endsAt).getTime() <= currentTime ? PAST_EVENT_COLOR_CLASSES[normalizeCalendarColor(previewEvent.color)] : EVENT_COLOR_CLASSES[normalizeCalendarColor(previewEvent.color)]}`}
style={{ top: previewPosition.top, height: previewPosition.height }}>
diff --git a/src/app/(calendar)/layout.tsx b/src/app/(calendar)/layout.tsx
index ae69298..cafd2b1 100644
--- a/src/app/(calendar)/layout.tsx
+++ b/src/app/(calendar)/layout.tsx
@@ -14,12 +14,12 @@ import { MailSearchProvider } from "@/components/mail-search/mail-search-context
import { MailboxProvider } from "@/components/mailbox-provider";
import { MailboxSelector } from "@/components/mailbox-selector";
import { SidebarAside, MobileMenuButton, MobileBrandIcon } from "@/components/sidebar-aside";
-import { DashboardNav } from "@/components/dashboard-nav";
import { SidebarHeader } from "@/components/sidebar-header";
import { SidebarProvider } from "@/components/sidebar-state";
import { ShortcutsProvider } from "@/components/shortcuts";
import { Button } from "@/components/ui/button";
import clsx from "clsx";
+import { CalendarMobileUpcoming } from "./calendar-mobile-upcoming";
import { useDashboardState } from "../(dashboard)/dashboard-state";
import { useAssistantAvailability } from "../(dashboard)/use-assistant-availability";
@@ -45,7 +45,7 @@ export default function CalendarLayout({ children }: { children: React.ReactNode
<MailSearchProvider>
<ShortcutsProvider>
<div className="grid h-dvh grid-cols-[minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]">
- <SidebarAside className="md:hidden"><div className="h-full overflow-y-auto overscroll-contain px-3 py-4"><DashboardNav /></div></SidebarAside>
+ <SidebarAside className="md:hidden"><CalendarMobileUpcoming /></SidebarAside>
<div className="flex min-h-0 min-w-0 flex-col">
<header className="flex h-16 w-full shrink-0 items-center gap-3 pr-4 text-sm max-md:h-auto max-md:flex-wrap max-md:gap-y-2 max-md:pb-2">
<MobileMenuButton className="ml-2" />
@@ -53,11 +53,13 @@ export default function CalendarLayout({ children }: { children: React.ReactNode
<div className="hidden shrink-0 px-3 md:block [&>div]:mb-0" style={{ width: "calc(var(--sidebar-width) + 1.5rem)" }}><SidebarHeader href="/inbox" /></div>
<div className="relative shrink-0 md:hidden"><select aria-label="Calendar section" value={pathname === "/booking" ? "/booking" : "/calendar"} onChange={(event) => router.push(event.target.value)} className="h-10 appearance-none rounded-full border-0 bg-white pl-4 pr-10 text-sm font-medium text-neutral-700"><option value="/booking">Bookings</option><option value="/calendar">Calendar</option></select><ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2 text-neutral-600" /></div>
<span className="flex-1 md:hidden" />
- <nav aria-label="Calendar sections" className="flex shrink-0 max-md:hidden items-center rounded-full bg-white p-1">
- <Link href="/booking" aria-current={pathname === "/booking" ? "page" : undefined} className={clsx("rounded-full px-4 py-2 text-sm font-medium transition-colors", pathname === "/booking" ? "bg-blue-600 text-white" : "text-neutral-600 hover:bg-neutral-100")}>Bookings</Link>
- <Link href="/calendar" aria-current={pathname === "/calendar" ? "page" : undefined} className={clsx("rounded-full px-4 py-2 text-sm font-medium transition-colors", pathname === "/calendar" ? "bg-blue-600 text-white" : "text-neutral-600 hover:bg-neutral-100")}>Calendar</Link>
- </nav>
- <div id="calendar-header-slot" className="flex min-w-0 flex-1 items-center max-md:order-last max-md:basis-full max-md:pl-3 max-md:empty:hidden" />
+ <div className="flex min-w-0 flex-1 items-center gap-3 md:overflow-x-auto max-md:contents">
+ <nav aria-label="Calendar sections" className="flex shrink-0 max-md:hidden items-center rounded-full bg-white p-1">
+ <Link href="/booking" aria-current={pathname === "/booking" ? "page" : undefined} className={clsx("rounded-full px-4 py-2 text-sm font-medium transition-colors", pathname === "/booking" ? "bg-blue-600 text-white" : "text-neutral-600 hover:bg-neutral-100")}>Bookings</Link>
+ <Link href="/calendar" aria-current={pathname === "/calendar" ? "page" : undefined} className={clsx("rounded-full px-4 py-2 text-sm font-medium transition-colors", pathname === "/calendar" ? "bg-blue-600 text-white" : "text-neutral-600 hover:bg-neutral-100")}>Calendar</Link>
+ </nav>
+ <div id="calendar-header-slot" className="flex min-w-0 flex-1 items-center md:min-w-max max-md:order-last max-md:basis-full max-md:pl-3 max-md:empty:hidden" />
+ </div>
<LicenseIndicator />
{assistantEnabled && <Button type="button" variant="ghost" size="sm" className={assistantOpen ? "bg-blue-50 text-blue-700" : "text-neutral-600"} onClick={() => { setAssistantOpen((current) => !current); setAssistantFullSize(false); }} aria-label={assistantOpen ? "Close email assistant" : "Open email assistant"} aria-expanded={assistantOpen} aria-controls="email-assistant-panel"><Sparkles className="h-5 w-5" /></Button>}
<MailboxSelector />
diff --git a/src/app/(calendar)/upcoming-sidebar-types.d.ts b/src/app/(calendar)/upcoming-sidebar-types.d.ts
index 0fbf6e2..3599497 100644
--- a/src/app/(calendar)/upcoming-sidebar-types.d.ts
+++ b/src/app/(calendar)/upcoming-sidebar-types.d.ts
@@ -3,4 +3,8 @@ import type { CalendarEvent } from "./calendar/types";
export type UpcomingSidebarProps = {
events?: CalendarEvent[];
onSelect?: (event: CalendarEvent) => void;
+ /** Render only the list, for the mobile menu drawer. */
+ drawer?: boolean;
+ /** Refetch (keeping the current list on screen) when this value changes. */
+ refreshKey?: unknown;
};
diff --git a/src/app/(calendar)/upcoming-sidebar.tsx b/src/app/(calendar)/upcoming-sidebar.tsx
index 01542f4..a12efe2 100644
--- a/src/app/(calendar)/upcoming-sidebar.tsx
+++ b/src/app/(calendar)/upcoming-sidebar.tsx
@@ -11,12 +11,14 @@ import type { CalendarEvent } from "./calendar/types";
import { addDays, expandCalendarEvents, formatEventRange, groupUpcomingEvents, startOfDay, takeUpcomingGroups, UPCOMING_BATCH_SIZE } from "./calendar/utils";
import type { UpcomingSidebarProps } from "./upcoming-sidebar-types";
-export function UpcomingSidebar({ events, onSelect }: UpcomingSidebarProps) {
+export function UpcomingSidebar({ events, onSelect, drawer = false, refreshKey }: UpcomingSidebarProps) {
const { minimal: sidebarMinimal, mobile } = useSidebar();
- const minimal = sidebarMinimal || mobile;
+ // The drawer variant is always expanded; it only mounts while the mobile menu is open.
+ const minimal = !drawer && (sidebarMinimal || mobile);
const router = useRouter();
const [loadedEvents, setLoadedEvents] = useState<CalendarEvent[]>([]);
const [loadError, setLoadError] = useState(false);
+ const [loaded, setLoaded] = useState(false);
const [visibleCount, setVisibleCount] = useState(UPCOMING_BATCH_SIZE);
const scrollRef = useRef<HTMLDivElement | null>(null);
const sentinelRef = useRef<HTMLDivElement | null>(null);
@@ -35,10 +37,10 @@ export function UpcomingSidebar({ events, onSelect }: UpcomingSidebarProps) {
if (!response.ok) throw new Error();
return response.json() as Promise<{ events?: CalendarEvent[] }>;
})
- .then((data) => { if (active) setLoadedEvents(expandCalendarEvents(data.events ?? [], today, end)); })
+ .then((data) => { if (active) { setLoadedEvents(expandCalendarEvents(data.events ?? [], today, end)); setLoadError(false); setLoaded(true); } })
.catch(() => { if (active) setLoadError(true); });
return () => { active = false; };
- }, [events, today]);
+ }, [events, today, refreshKey]);
useEffect(() => { setVisibleCount(UPCOMING_BATCH_SIZE); }, [shownEvents]);
@@ -53,11 +55,17 @@ export function UpcomingSidebar({ events, onSelect }: UpcomingSidebarProps) {
return () => observer.disconnect();
}, [minimal, total, visibleCount]);
- return <aside className={clsx("relative shrink-0 rounded-t-3xl bg-white transition-[width,max-height] duration-200 ease-in-out motion-reduce:transition-none lg:h-full lg:max-h-none", minimal ? "w-0 max-h-0" : "w-full max-h-[36vh] lg:w-[var(--sidebar-width)]")} aria-hidden={minimal}>
- {!minimal && <div ref={scrollRef} className="h-full overflow-y-auto overscroll-contain rounded-t-3xl px-5 py-5">
- {groups.length === 0 ? <div><h2 className="text-lg font-semibold text-neutral-900">Upcoming</h2><p className="mt-4 text-sm text-neutral-400">{loadError ? "Could not load upcoming events." : "No upcoming events."}</p></div> : visibleGroups.map((group) => <section key={group.key} className="mb-6 last:mb-0"><h2 className="sticky -top-5 z-10 -mx-5 mb-2 bg-white px-5 py-2 text-base font-semibold text-neutral-900">{group.label}</h2><div className="space-y-2">{group.events.map((event) => <button key={event.id} type="button" onClick={() => onSelect ? onSelect(event) : router.push(`/calendar?event=${encodeURIComponent(event.id)}`)} className="group flex w-full items-start gap-3 text-left"><span className="mt-0.5 h-4 w-4 shrink-0 rounded-full border-2 border-white ring-1 ring-neutral-200" style={{ backgroundColor: normalizeCalendarColor(event.color) }} /><span className="min-w-0"><span className="block truncate text-sm text-neutral-700 group-hover:text-neutral-950">{event.title}</span><span className="block text-xs text-neutral-400">{formatEventRange(event)}</span></span></button>)}</div></section>)}
+ const awaiting = events === undefined && !loaded && !loadError;
+ const SKELETON = <div className="space-y-6" aria-label="Loading upcoming events" aria-busy="true">{[0, 1].map((group) => <div key={group} className="animate-pulse"><div className="mb-3 h-4 w-28 rounded bg-neutral-200" /><div className="space-y-3">{[0, 1, 2].map((row) => <div key={row} className="flex items-start gap-3"><span className="mt-0.5 h-4 w-4 shrink-0 rounded-full bg-neutral-200" /><span className="min-w-0 flex-1 space-y-1.5"><span className="block h-3.5 w-3/4 rounded bg-neutral-200" /><span className="block h-3 w-1/2 rounded bg-neutral-100" /></span></div>)}</div></div>)}</div>;
+ const list = !minimal && <div ref={scrollRef} className="h-full overflow-y-auto overscroll-contain rounded-t-3xl px-5 py-5">
+ {awaiting ? SKELETON : groups.length === 0 ? <div><h2 className="text-lg font-semibold text-neutral-900">Upcoming</h2><p className="mt-4 text-sm text-neutral-400">{loadError ? "Could not load upcoming events." : "No upcoming events."}</p></div> : visibleGroups.map((group) => <section key={group.key} className="mb-6 last:mb-0"><h2 className="sticky -top-5 z-10 -mx-5 mb-2 bg-white px-5 py-2 text-base font-semibold text-neutral-900">{group.label}</h2><div className="space-y-2">{group.events.map((event) => <button key={event.id} type="button" onClick={() => onSelect ? onSelect(event) : router.push(`/calendar?event=${encodeURIComponent(event.id)}`)} className="group flex w-full items-start gap-3 text-left"><span className="mt-0.5 h-4 w-4 shrink-0 rounded-full border-2 border-white ring-1 ring-neutral-200" style={{ backgroundColor: normalizeCalendarColor(event.color) }} /><span className="min-w-0"><span className="block truncate text-sm text-neutral-700 group-hover:text-neutral-950">{event.title}</span><span className="block text-xs text-neutral-400">{formatEventRange(event)}</span></span></button>)}</div></section>)}
{visibleCount < total && <div ref={sentinelRef} aria-hidden="true" className="h-1" />}
- </div>}
+ </div>;
+
+ if (drawer) return <div className="h-full min-h-0 bg-white">{list}</div>;
+
+ return <aside className={clsx("relative shrink-0 rounded-t-3xl bg-white transition-[width,max-height] duration-200 ease-in-out motion-reduce:transition-none lg:h-full lg:max-h-none", minimal ? "w-0 max-h-0" : "w-full max-h-[36vh] lg:w-[var(--sidebar-width)]")} aria-hidden={minimal}>
+ {list}
{!minimal && <div className="hidden lg:block"><SidebarResizeBoundary /></div>}
</aside>;
}