Email for professionals and teams
update calendar
Hieu Nguyen (Jack)ccca978b777a
diff --git a/README.md b/README.mdindex cd3e626..9be9f32 100644--- a/README.md+++ b/README.md@@ -56,6 +56,32 @@ Getting started takes three steps:- All accounts - Email Sending:Edit, DNS Settings:Edit, Email Routing Addresses:Edit- All zones - DNS Settings:Edit, Email Routing Rules:Edit, Zone Settings:Edit, DNS:Edit+### Deploy with an AI coding agent++You can paste the prompt below into an agent that has terminal access. Give it the Cloudflare account ID and **two separate scoped API tokens** through the agent's secret input, not in a public chat, repository, or committed file:++- **Deployment token** (used locally by Wrangler as `CLOUDFLARE_API_TOKEN`): scope it to the target account with **Workers Scripts Edit** (or **Workers Admin** if Cloudflare's newer granular roles are shown, since this is a new Worker), **D1 Edit**, **Workers R2 Storage Edit**, **Queues Edit**, and **Account Settings Read**. Add **Workers Routes Edit** for the target zone only if you want the agent to attach a custom domain or route. See Cloudflare's [token permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/) and [Workers roles](https://developers.cloudflare.com/workers/authorization/workers/).+- **Runtime token** (stored as the Worker's `CF_TOKEN` secret): use the domain permissions listed above. Add **Email Sending Edit** if you want to send mail. This token is separate from the deployment token and must cover the zones you will connect in Mailflare.++```text+Install Mailflare from https://github.com/hieunc229/mailflare in my Cloudflare account.+Ask me for my Cloudflare account ID, a scoped deployment API token, and a separate+runtime CF_TOKEN through a secret input. Never print, commit, or place either token+in a command argument or a tracked file. Use the deployment token only for Wrangler+authentication (CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID).++Read README.md, docs/deployment.md, and wrangler.jsonc first. Keep the Worker name+exactly mailflare. In the selected account, create or reuse the D1 database+mailflare, R2 bucket mailflare-raw, and Queues mailflare-inbound,+mailflare-outbound, and mailflare-agent. Set the D1 database_id in the local+Wrangler config without committing that account-specific ID. Install dependencies,+run npm run deploy, and set the runtime CF_TOKEN as a Worker secret. Do not run+remote D1 migrations manually; the /setup flow initializes the database.++Give me the deployed URL and any remaining Cloudflare account actions. I will+open /setup, create the first admin account, and connect my domain there.+```+See the [deployment guide](docs/deployment.md) for required permissions, manual deployment, backups, and updates.### Self-host with Docker insteaddiff --git a/drizzle/migrations/0044_add_calendar_repeat.sql b/drizzle/migrations/0044_add_calendar_repeat.sqlnew file mode 100644index 0000000..91f586c--- /dev/null+++ b/drizzle/migrations/0044_add_calendar_repeat.sql@@ -0,0 +1,2 @@+ALTER TABLE `calendar_events` ADD `repeat` text NOT NULL DEFAULT 'none';+ALTER TABLE `calendar_events` ADD `repeat_until` integer;diff --git a/drizzle/migrations/0045_add_calendar_repeat_days.sql b/drizzle/migrations/0045_add_calendar_repeat_days.sqlnew file mode 100644index 0000000..82f5de9--- /dev/null+++ b/drizzle/migrations/0045_add_calendar_repeat_days.sql@@ -0,0 +1,2 @@+ALTER TABLE `calendar_events` ADD `repeat_days` text NOT NULL DEFAULT '[]';+ALTER TABLE `calendar_events` ADD `repeat_anchor_day` integer;diff --git a/drizzle/migrations/0046_add_calendar_excluded_occurrences.sql b/drizzle/migrations/0046_add_calendar_excluded_occurrences.sqlnew file mode 100644index 0000000..8b36fa7--- /dev/null+++ b/drizzle/migrations/0046_add_calendar_excluded_occurrences.sql@@ -0,0 +1 @@+ALTER TABLE `calendar_events` ADD `excluded_occurrences` text NOT NULL DEFAULT '[]';diff --git a/package-lock.json b/package-lock.jsonindex 411dee8..38f4daa 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "mailflare",- "version": "0.3.0",+ "version": "0.4.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "mailflare",- "version": "0.3.0",+ "version": "0.4.0","license": "SEE LICENSE IN LICENSE","dependencies": {"@ai-sdk/openai-compatible": "^3.0.55",@@ -38,6 +38,7 @@"qrcode": "^1.5.4","react": "^19.2.6","react-dom": "^19.2.6",+ "react-hot-toast": "^2.6.1","react-markdown": "^10.1.0","react-server-dom-webpack": "^19.2.6","remark-gfm": "^4.0.1",@@ -8396,6 +8397,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/goober": {+ "version": "2.1.19",+ "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.19.tgz",+ "integrity": "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg==",+ "license": "MIT",+ "peerDependencies": {+ "csstype": "^3.0.10"+ }+ },"node_modules/gopd": {"version": "1.2.0","resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",@@ -12222,6 +12232,33 @@"react": "^19.3.0"}},+ "node_modules/react-hot-toast": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.1.tgz",+ "integrity": "sha512-gjFsf05dxcku0FkyMtFH+XmYFdA2odXfBVknEr/IZ+XpUjwsgvtY2616sOpUynK+l9ykQDRNpaJ1hYfuximUiA==",+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.1.3",+ "goober": "^2.1.16"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": ">=16",+ "react-dom": ">=16"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/react-is": {"version": "16.13.1","resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",diff --git a/package.json b/package.jsonindex a6c25e1..9a160ec 100644--- a/package.json+++ b/package.json@@ -86,6 +86,7 @@"qrcode": "^1.5.4","react": "^19.2.6","react-dom": "^19.2.6",+ "react-hot-toast": "^2.6.1","react-markdown": "^10.1.0","react-server-dom-webpack": "^19.2.6","remark-gfm": "^4.0.1",diff --git a/src/app/(dashboard)/calendar/page.tsx b/src/app/(dashboard)/calendar/page.tsxindex b2fb76c..9adc2b5 100644--- a/src/app/(dashboard)/calendar/page.tsx+++ b/src/app/(dashboard)/calendar/page.tsx@@ -3,54 +3,74 @@import { Fragment, useEffect, useMemo, useRef, useState } from "react";import type { PointerEvent as ReactPointerEvent } from "react";import { createPortal } from "react-dom";-import { ChevronDown, ChevronLeft, ChevronRight, Plus, Trash2 } from "lucide-react";+import toast, { Toaster } from "react-hot-toast";+import { AlignLeft, ChevronDown, ChevronLeft, ChevronRight, Clock3, MapPin, Palette, Plus, Repeat2, Trash2, UsersRound, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";import { authFetch } from "@/lib/auth/client";+import { normalizeCalendarColor } from "@/lib/calendar/colors";+import { DEFAULT_REPEAT_DAYS, parseCalendarRepeatDays } from "@/lib/calendar/recurrence";+import { DEFAULT_FOLDER_COLOR, FOLDER_COLOR_OPTIONS } from "@/lib/folders/colors";+import type { CalendarRepeat } from "@/lib/calendar/types";import { useSelectedMailbox } from "@/components/mailbox-provider";import { useSidebar } from "@/components/sidebar-state";import { SidebarResizeBoundary } from "@/components/sidebar-resize-boundary";import type { CalendarEvent, CalendarView, EventDragPreview, EventResizeEdge, EventResizeSession } from "./types";import {addDays, CALENDAR_END_HOUR, CALENDAR_HOUR_HEIGHT, CALENDAR_START_HOUR,- dateKey, dropStartForPosition, EVENT_COLORS, EVENT_COLOR_DOTS, eventPosition,+ currentTimePosition, dateKey, dropStartForPosition, EVENT_COLOR_CLASSES, eventEndAfterMinutes, eventPosition, expandCalendarEvents,formatEventRange, formatHour, formatLocalDateTime, groupUpcomingEvents,- monthGridDates, resizeEventTimes, startOfDay, startOfWorkweek,+ monthGridDates, nextCalendarOccurrence, PAST_EVENT_COLOR_CLASSES, resizeEventTimes, startOfDay, startOfWeek, takeUpcomingGroups, UPCOMING_BATCH_SIZE, WEEKDAY_OPTIONS,} from "./utils";import clsx from "clsx";+const eventFieldClass = "h-9 border-transparent bg-transparent px-2 shadow-none hover:bg-white/60 focus:border-blue-600 focus:bg-white focus:shadow-sm";+export default function CalendarPage() {const [events, setEvents] = useState<CalendarEvent[]>([]);+ const [eventsVersion, setEventsVersion] = useState(0);+ const [currentTime, setCurrentTime] = useState(() => Date.now());const [visibleDate, setVisibleDate] = useState(() => new Date());const [view, setView] = useState<CalendarView>("week");const [monthPickerOpen, setMonthPickerOpen] = useState(false);const [pickerMonth, setPickerMonth] = useState(() => new Date());const monthPickerRef = useRef<HTMLDivElement | null>(null);+ const upcomingScrollRef = useRef<HTMLDivElement | null>(null);+ const upcomingSentinelRef = useRef<HTMLDivElement | null>(null);const [headerTarget, setHeaderTarget] = useState<HTMLElement | null>(null);const [draggedEvent, setDraggedEvent] = useState<CalendarEvent | null>(null);const [resizingEvent, setResizingEvent] = useState<CalendarEvent | null>(null);const [dragPreview, setDragPreview] = useState<EventDragPreview | null>(null);const dragOffsetPixels = useRef(0);const resizeSession = useRef<EventResizeSession | null>(null);- const [errorMessage, setErrorMessage] = useState("");const [title, setTitle] = useState("");- const [color, setColor] = useState("blue");+ const [color, setColor] = useState<string>(DEFAULT_FOLDER_COLOR);+ const [repeat, setRepeat] = useState<CalendarRepeat>("none");+ const [repeatDays, setRepeatDays] = useState<number[]>(DEFAULT_REPEAT_DAYS);const [startsAt, setStartsAt] = useState("");const [endsAt, setEndsAt] = useState("");const [adding, setAdding] = useState(false);+ const [closingEventEditor, setClosingEventEditor] = useState(false);const [guests, setGuests] = useState("");+ const [location, setLocation] = useState("");+ const [description, setDescription] = useState("");const [editing, setEditing] = useState<CalendarEvent | null>(null);const [pendingAction, setPendingAction] = useState<"save" | string | null>(null);+ const [visibleUpcomingCount, setVisibleUpcomingCount] = useState(UPCOMING_BATCH_SIZE);const { selectedMailbox } = useSelectedMailbox();const { minimal } = useSidebar();const today = useMemo(() => startOfDay(new Date()), []);- const workweekStart = useMemo(() => startOfWorkweek(visibleDate), [visibleDate]);+ const now = new Date(currentTime);+ const weekStart = useMemo(() => startOfWeek(visibleDate), [visibleDate]);const days = useMemo(- () => view === "day" ? [startOfDay(visibleDate)] : Array.from({ length: 5 }, (_, index) => addDays(workweekStart, index)),- [view, visibleDate, workweekStart],+ () => view === "day" ? [startOfDay(visibleDate)] : Array.from({ length: 7 }, (_, index) => addDays(weekStart, index)),+ [view, visibleDate, weekStart],);const upcomingGroups = useMemo(() => groupUpcomingEvents(events, today), [events, today]);+ const upcomingTotal = useMemo(() => upcomingGroups.reduce((count, group) => count + group.events.length, 0), [upcomingGroups]);+ const visibleUpcomingGroups = useMemo(() => takeUpcomingGroups(upcomingGroups, visibleUpcomingCount), [upcomingGroups, visibleUpcomingCount]);const pickerDates = useMemo(() => monthGridDates(pickerMonth), [pickerMonth]);const previewEvent = useMemo(() => dragPreview && (draggedEvent || resizingEvent)? {@@ -67,6 +87,26 @@ export default function CalendarPage() {setHeaderTarget(document.getElementById("calendar-header-slot"));}, []);+ useEffect(() => {+ const interval = window.setInterval(() => setCurrentTime(Date.now()), 60_000);+ return () => window.clearInterval(interval);+ }, []);++ useEffect(() => {+ setVisibleUpcomingCount(UPCOMING_BATCH_SIZE);+ }, [events]);++ useEffect(() => {+ if (minimal || visibleUpcomingCount >= upcomingTotal || !upcomingScrollRef.current || !upcomingSentinelRef.current) return;+ const observer = new IntersectionObserver(([entry]) => {+ if (!entry?.isIntersecting) return;+ observer.disconnect();+ setVisibleUpcomingCount((count) => Math.min(count + UPCOMING_BATCH_SIZE, upcomingTotal));+ }, { root: upcomingScrollRef.current, rootMargin: "0px 0px 100px 0px" });+ observer.observe(upcomingSentinelRef.current);+ return () => observer.disconnect();+ }, [minimal, upcomingTotal, visibleUpcomingCount]);+useEffect(() => {if (!monthPickerOpen) return;const closeOnOutsidePointer = (event: PointerEvent) => {@@ -84,69 +124,95 @@ export default function CalendarPage() {}, [monthPickerOpen]);useEffect(() => {- const start = new Date(Math.min(today.getTime(), workweekStart.getTime(), startOfDay(visibleDate).getTime()));- const end = new Date(Math.max(addDays(today, 90).getTime(), addDays(workweekStart, 7).getTime(), addDays(visibleDate, 1).getTime()));+ const start = new Date(Math.min(today.getTime(), weekStart.getTime(), startOfDay(visibleDate).getTime()));+ const end = new Date(Math.max(addDays(today, 90).getTime(), addDays(weekStart, 7).getTime(), addDays(visibleDate, 1).getTime()));void authFetch(`/api/calendar/events?start=${start.toISOString()}&end=${end.toISOString()}`)- .then((response) => response.json())- .then((data) => setEvents(data.events ?? []));- }, [today, visibleDate, workweekStart]);+ .then((response) => {+ if (!response.ok) throw new Error("Could not load calendar events.");+ return response.json();+ })+ .then((data) => setEvents(expandCalendarEvents(data.events ?? [], start, end)))+ .catch(() => toast.error("Could not load calendar events."));+ }, [today, visibleDate, weekStart, eventsVersion]);function openNewEvent(day = visibleDate, startAt?: Date) {const start = startAt ? new Date(startAt) : new Date(day);if (!startAt) start.setHours(Math.min(Math.max(new Date().getHours() + 1, CALENDAR_START_HOUR), CALENDAR_END_HOUR - 1), 0, 0, 0);setEditing(null);setTitle("");- setColor("blue");+ setColor(DEFAULT_FOLDER_COLOR);+ setRepeat("none");+ setRepeatDays(DEFAULT_REPEAT_DAYS);setGuests("");+ setLocation("");+ setDescription("");setStartsAt(formatLocalDateTime(start));setEndsAt(formatLocalDateTime(new Date(start.getTime() + 60 * 60_000)));+ setClosingEventEditor(false);setAdding(true);}async function addEvent() {setPendingAction("save");try {+ const editedStart = editing && startsAt === formatLocalDateTime(new Date(editing.startsAt)) ? new Date(editing.startsAt) : new Date(startsAt);+ const editedEnd = editing && endsAt === formatLocalDateTime(new Date(editing.endsAt)) ? new Date(editing.endsAt) : new Date(endsAt);+ const movingToPast = Boolean(editing && editing.repeat !== "none" && editedStart.getTime() < Date.now() && editedStart.getTime() !== new Date(editing.startsAt).getTime());+ const effectiveFrom = editing && editing.repeat !== "none" && !movingToPast ? new Date() : null;+ let savedStart = editedStart;+ let savedEnd = editedEnd;+ if (editing && effectiveFrom) {+ const offset = editedStart.getTime() - new Date(editing.startsAt).getTime();+ const next = nextCalendarOccurrence(editing, new Date(effectiveFrom.getTime() - offset));+ if (!next) { toast.error("No future occurrences remain to update."); return; }+ savedStart = new Date(next.getTime() + offset);+ savedEnd = new Date(savedStart.getTime() + editedEnd.getTime() - editedStart.getTime());+ }+ const repeatAnchorDay = editing?.repeat === "monthly" && startsAt.slice(0, 10) === formatLocalDateTime(new Date(editing.startsAt)).slice(0, 10)+ ? editing.repeatAnchorDay ?? new Date(editing.seriesStartsAt ?? editing.startsAt).getDate()+ : editedStart.getDate();const response = await authFetch(editing ? `/api/calendar/events/${editing.id}` : "/api/calendar/events", {method: editing ? "PATCH" : "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({- title, startsAt, endsAt, color, attendees: guests.split(","),- description: editing?.description ?? "",- location: editing?.location ?? "",+ title, startsAt: savedStart.toISOString(), endsAt: savedEnd.toISOString(), color, repeat, repeatDays, repeatAnchorDay, effectiveFrom: effectiveFrom?.toISOString(), moveOccurrenceToPast: movingToPast, attendees: guests.split(","),+ description,+ location,mailboxId: selectedMailbox?.id,from: selectedMailbox?.senderAddresses?.[0] ??(selectedMailbox ? `${selectedMailbox.localPart}@${selectedMailbox.hostname}` : ""),}),});- const data = await response.json();if (response.ok) {- setEvents((items) => (editing- ? items.map((event) => event.id === editing.id ? {- ...event, title, color,- startsAt: new Date(startsAt).toISOString(),- endsAt: new Date(endsAt).toISOString(),- attendees: JSON.stringify(guests.split(",").filter(Boolean)),- } : event)- : [...items, data.event]- ).sort((a, b) => a.startsAt.localeCompare(b.startsAt)));- setAdding(false);- setEditing(null);+ setEventsVersion((version) => version + 1);+ setClosingEventEditor(true);+ } else {+ const result = await response.json();+ toast.error(result.error ?? "Could not save the event. Please try again.");}+ } catch {+ toast.error("Could not save the event. Please try again.");} finally {setPendingAction(null);}}async function deleteEvent(id: string) {- if (!window.confirm("Delete this event?")) return;+ const recurring = editing && editing.repeat !== "none";+ if (!window.confirm(recurring ? "Delete future occurrences from now?" : "Delete this event?")) return;setPendingAction(id);try {- const response = await authFetch(`/api/calendar/events/${id}`, { method: "DELETE" });+ const effectiveFrom = recurring ? new Date().toISOString() : undefined;+ const response = await authFetch(`/api/calendar/events/${id}`, { method: "DELETE", headers: effectiveFrom ? { "Content-Type": "application/json" } : undefined, body: effectiveFrom ? JSON.stringify({ effectiveFrom }) : undefined });if (response.ok) {- setEvents((items) => items.filter((event) => event.id !== id));- setAdding(false);- setEditing(null);+ setEventsVersion((version) => version + 1);+ setClosingEventEditor(true);+ } else {+ const result = await response.json();+ toast.error(result.error ?? "Could not delete the event. Please try again.");}+ } catch {+ toast.error("Could not delete the event. Please try again.");} finally {setPendingAction(null);}@@ -155,10 +221,15 @@ export default function CalendarPage() {function editEvent(event: CalendarEvent) {setEditing(event);setTitle(event.title);- setColor(event.color ?? "blue");+ setColor(normalizeCalendarColor(event.color));+ setRepeat(event.repeat);+ setRepeatDays(event.repeat === "weekdays" ? parseCalendarRepeatDays(event.repeatDays) : DEFAULT_REPEAT_DAYS);+ setLocation(event.location ?? "");+ setDescription(event.description ?? "");setStartsAt(formatLocalDateTime(new Date(event.startsAt)));setEndsAt(formatLocalDateTime(new Date(event.endsAt)));setGuests(JSON.parse(event.attendees || "[]").join(", "));+ setClosingEventEditor(false);setAdding(true);}@@ -170,8 +241,18 @@ export default function CalendarPage() {return;}setPendingAction(event.id);- setErrorMessage("");try {+ const movingToPast = event.repeat !== "none" && startsAt.getTime() < Date.now();+ const effectiveFrom = event.repeat !== "none" && !movingToPast ? new Date() : null;+ let savedStart = startsAt;+ let savedEnd = endsAt;+ if (effectiveFrom) {+ const offset = startsAt.getTime() - new Date(event.startsAt).getTime();+ const next = nextCalendarOccurrence(event, new Date(effectiveFrom.getTime() - offset));+ if (!next) { toast.error("No future occurrences remain to update."); return; }+ savedStart = new Date(next.getTime() + offset);+ savedEnd = new Date(savedStart.getTime() + endsAt.getTime() - startsAt.getTime());+ }const response = await authFetch(`/api/calendar/events/${event.id}`, {method: "PATCH",headers: { "Content-Type": "application/json" },@@ -181,21 +262,26 @@ export default function CalendarPage() {location: event.location,attendees: JSON.parse(event.attendees || "[]"),color: event.color,- startsAt: startsAt.toISOString(),- endsAt: endsAt.toISOString(),+ repeat: event.repeat,+ repeatDays: parseCalendarRepeatDays(event.repeatDays),+ repeatAnchorDay: event.repeat === "monthly" && dateKey(startsAt) === dateKey(new Date(event.startsAt))+ ? event.repeatAnchorDay ?? new Date(event.seriesStartsAt ?? event.startsAt).getDate()+ : startsAt.getDate(),+ effectiveFrom: effectiveFrom?.toISOString(),+ moveOccurrenceToPast: movingToPast,+ startsAt: savedStart.toISOString(),+ endsAt: savedEnd.toISOString(),from: selectedMailbox?.senderAddresses?.[0] ??(selectedMailbox ? `${selectedMailbox.localPart}@${selectedMailbox.hostname}` : ""),}),});if (!response.ok) {- setErrorMessage("Could not update the event time. Please try again.");+ toast.error("Could not update the event time. Please try again.");return;}- setEvents((items) => items.map((item) => item.id === event.id- ? { ...item, startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString() }- : item).sort((a, b) => a.startsAt.localeCompare(b.startsAt)));+ setEventsVersion((version) => version + 1);} catch {- setErrorMessage("Could not update the event time. Please try again.");+ toast.error("Could not update the event time. Please try again.");} finally {setDraggedEvent(null);setResizingEvent(null);@@ -259,6 +345,7 @@ export default function CalendarPage() {return (<div className={clsx("flex h-full min-h-0 flex-col bg-[#f6f8fc] pl-3 lg:flex-row transition-[gap] duration-200 ease-in-out motion-reduce:transition-none", minimal ? "gap-0" : "gap-3")}>+ <Toaster position="bottom-right" />{headerTarget && createPortal(<div className="flex min-w-0 flex-1 items-center justify-between gap-3"><div ref={monthPickerRef} className="relative shrink-0">@@ -323,19 +410,19 @@ export default function CalendarPage() {)}<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 className="h-full overflow-y-auto overscroll-contain rounded-t-3xl px-5 py-5">+ <div ref={upcomingScrollRef} className="h-full overflow-y-auto overscroll-contain rounded-t-3xl px-5 py-5">{upcomingGroups.length === 0 ? (<div><h2 className="text-lg font-semibold text-neutral-900">Upcoming</h2><p className="mt-4 text-sm text-neutral-400">No upcoming events.</p></div>- ) : upcomingGroups.map((group) => (+ ) : visibleUpcomingGroups.map((group) => (<section key={group.key} className="mb-6 last:mb-0">- <h2 className="mb-3 text-base font-semibold text-neutral-900">{group.label}</h2>+ <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={() => editEvent(event)} 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 ${EVENT_COLOR_DOTS[event.color as keyof typeof EVENT_COLOR_DOTS] ?? EVENT_COLOR_DOTS.blue}`} />+ <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>@@ -345,21 +432,21 @@ export default function CalendarPage() {</div></section>))}+ {visibleUpcomingCount < upcomingTotal && <div ref={upcomingSentinelRef} aria-hidden="true" className="h-1" />}</div>)}{!minimal && <div className="hidden lg:block"><SidebarResizeBoundary /></div>}</aside><section className="min-h-0 min-w-0 flex-1 rounded-t-3xl bg-white flex flex-col overflow-hidden">- {errorMessage && <div role="alert" className="border-b border-red-100 bg-red-50 px-4 py-2 text-sm text-red-700">{errorMessage}</div>}<div className="sticky top-0 z-30 grid border-b border-neutral-200 bg-white h-14" style={{ gridTemplateColumns: `64px repeat(${days.length}, minmax(0, 1fr))` }}><div />{days.map((day) => (- <div key={dateKey(day)} className={`border-l border-neutral-100 px-3 py-2 text-xs ${dateKey(day) === dateKey(today) ? "text-blue-600" : "text-neutral-500"}`}>+ <div key={dateKey(day)} className={`border-l border-neutral-100 px-3 py-2 text-xs ${dateKey(day) === dateKey(today) ? "text-blue-700" : "text-neutral-700"}`}>{day.toLocaleDateString(undefined, { weekday: "short" })}- <b className="text-xl block">+ <span className="text-2xl block font-medium">{day.toLocaleDateString(undefined, { day: "numeric" })}- </b>+ </span></div>))}</div>@@ -372,7 +459,7 @@ export default function CalendarPage() {))}</div>{days.map((day) => (- <div key={dateKey(day)} className="relative border-l border-neutral-100"+ <div key={dateKey(day)} className={"relative border-l border-neutral-100"}onDragOver={(event) => {if (!draggedEvent) return;event.preventDefault();@@ -391,7 +478,8 @@ export default function CalendarPage() {{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 color = EVENT_COLORS[event.color as keyof typeof EVENT_COLORS] ?? EVENT_COLORS.blue;+ 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 (@@ -400,9 +488,9 @@ export default function CalendarPage() {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 ${position.height >= 20 ? "py-1.5" : "py-0"} ${draggedEvent?.id === event.id || resizingEvent?.id === event.id ? "opacity-40" : ""} ${color}`}+ 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={clsx("absolute top-1 left-1 border-l-4 rounded-xl w-1 h-[calc(100%-8px)] block bg-amber-400", color)} />+ <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>@@ -421,7 +509,7 @@ export default function CalendarPage() {);})}{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 opacity-80 ${EVENT_COLORS[previewEvent.color as keyof typeof EVENT_COLORS] ?? EVENT_COLORS.blue}`}+ <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 }}><span className="absolute left-1 top-0 z-10 whitespace-nowrap rounded bg-neutral-900 px-1.5 py-0.5 text-[10px] font-medium text-white">{formatEventRange(previewEvent)}@@ -429,6 +517,12 @@ export default function CalendarPage() {{previewPosition.height >= 50 && <span className="block truncate px-2 pt-6 text-[12px] font-semibold">{previewEvent.title}</span>}</div>)}+ {dateKey(day) === dateKey(now) && (+ <div aria-hidden="true" className="pointer-events-none absolute inset-x-0 z-30" style={{ top: currentTimePosition(now) }}>+ <div className="h-1 w-full bg-blue-600" />+ <div className="absolute -left-2.5 -top-2 h-5 w-5 rounded-full bg-blue-600" />+ </div>+ )}</div>))}</div>@@ -436,33 +530,94 @@ export default function CalendarPage() {</section>{adding && (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-neutral-950/35 p-4">- <div className="w-full max-w-lg rounded-2xl bg-white p-6 shadow-2xl">- <h2 className="text-lg font-semibold">{editing ? "Edit event" : "Create event"}</h2>- <div className="mt-5 grid gap-3">- <Input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Event title" />- <Input value={guests} onChange={(event) => setGuests(event.target.value)} placeholder="Add guests (comma-separated emails)" />- <div>- <span className="mb-2 block text-sm font-medium text-neutral-700">Color</span>- <div role="radiogroup" aria-label="Event color" className="flex items-center gap-2">- {Object.entries(EVENT_COLOR_DOTS).map(([value, dotClass]) => (- <button key={value} type="button" role="radio" aria-label={value} aria-checked={color === value} onClick={() => setColor(value)}- className={`flex h-8 w-8 items-center justify-center rounded-full ${color === value ? "ring-2 ring-neutral-700 ring-offset-2" : "hover:ring-2 hover:ring-neutral-200"}`}>- <span className={`h-6 w-6 rounded-full ${dotClass}`} />- </button>- ))}+ <div className={clsx("dialog-overlay fixed inset-0 z-50 flex items-center justify-center bg-neutral-950/35 p-4", closingEventEditor && "pointer-events-none")} data-state={closingEventEditor ? "closed" : "open"}>+ <div role="dialog" aria-modal="true" aria-label={editing ? "Edit event" : "Create event"} className="dialog-content max-h-[calc(100dvh-2rem)] w-full max-w-xl overflow-y-auto rounded-2xl bg-white p-5 shadow-2xl sm:p-6" data-state={closingEventEditor ? "closed" : "open"}+ onAnimationEnd={(event) => {+ if (!closingEventEditor || event.target !== event.currentTarget) return;+ setAdding(false);+ setEditing(null);+ setClosingEventEditor(false);+ }}>+ <div className="flex items-start gap-3">+ <input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Add title" aria-label="Event name"+ className="min-w-0 flex-1 rounded-md border border-transparent bg-transparent px-2 py-1 text-2xl font-medium text-neutral-900 outline-none placeholder:text-neutral-500 hover:bg-white/60 focus:border-blue-600 focus:bg-white" />+ <button type="button" aria-label="Close event editor" disabled={pendingAction === "save"} onClick={() => setClosingEventEditor(true)} className="shrink-0 rounded-full p-1 text-neutral-600 hover:bg-neutral-200 disabled:opacity-50"><X className="h-5 w-5" /></button>+ </div>+ <div className="mt-4 space-y-2">+ <div className="grid grid-cols-[24px_minmax(0,1fr)] items-start gap-3">+ <Repeat2 aria-hidden="true" className="mt-2 h-5 w-5 text-neutral-600" />+ <div className="min-w-0">+ <select value={repeat} onChange={(event) => setRepeat(event.target.value as CalendarRepeat)} aria-label="Repeat"+ className="h-9 w-full rounded-md border border-transparent bg-transparent px-2 text-sm text-neutral-700 outline-none hover:bg-neutral-50 focus:border-blue-600 focus:bg-white">+ <option value="none">Does not repeat</option>+ <option value="daily">Daily</option>+ <option value="weekly">Weekly</option>+ <option value="monthly">Monthly</option>+ <option value="weekdays">Weekdays</option>+ </select>+ {repeat === "weekdays" && (+ <div role="group" aria-label="Repeat on weekdays" className="flex flex-wrap gap-1.5 px-2 pt-1">+ {WEEKDAY_OPTIONS.map((day) => (+ <button key={day.value} type="button" aria-label={`Repeat on ${day.label}`} aria-pressed={repeatDays.includes(day.value)}+ onClick={() => setRepeatDays((selected) => selected.includes(day.value) ? selected.filter((value) => value !== day.value) : [...selected, day.value].sort((a, b) => a - b))}+ className={clsx("rounded-full px-2.5 py-1 text-xs font-medium", repeatDays.includes(day.value) ? "bg-blue-600 text-white" : "bg-neutral-100 text-neutral-600 hover:bg-neutral-200")}>+ {day.label}+ </button>+ ))}+ </div>+ )}+ </div>+ </div>+ <div className="grid grid-cols-[24px_minmax(0,1fr)] items-start gap-3">+ <Clock3 aria-hidden="true" className="mt-2 h-5 w-5 text-neutral-600" />+ <div className="group min-w-0">+ <div className="grid gap-1 sm:grid-cols-2">+ <label className="relative block min-w-0">+ <span className="pointer-events-none absolute left-2 top-1/2 z-10 -translate-y-1/2 text-xs font-medium text-neutral-500">From</span>+ <Input type="datetime-local" value={startsAt} onChange={(event) => setStartsAt(event.target.value)} aria-label="From date and time" className={`${eventFieldClass} pl-14`} />+ </label>+ <label className="relative block min-w-0">+ <span className="pointer-events-none absolute left-2 top-1/2 z-10 -translate-y-1/2 text-xs font-medium text-neutral-500">To</span>+ <Input type="datetime-local" value={endsAt} onChange={(event) => setEndsAt(event.target.value)} aria-label="To date and time" className={`${eventFieldClass} pl-14`} />+ </label>+ </div>+ <div className="hidden flex-wrap gap-1 pt-1 group-focus-within:flex" aria-label="Set event duration">+ {([{ label: "15 mins", minutes: 15 }, { label: "30 mins", minutes: 30 }, { label: "1 hour", minutes: 60 }, { label: "1 day", minutes: 1440 }] as const).map((preset) => (+ <Button key={preset.minutes} type="button" variant="ghost" disabled={!startsAt || Number.isNaN(new Date(startsAt).getTime())} onClick={() => setEndsAt(eventEndAfterMinutes(startsAt, preset.minutes))} className="h-7 rounded-full px-2 text-xs text-neutral-600 hover:bg-neutral-100">+ {preset.label}+ </Button>+ ))}+ </div></div></div>- <div className="grid grid-cols-2 gap-3">- <Input type="datetime-local" value={startsAt} onChange={(event) => setStartsAt(event.target.value)} aria-label="Start date and time" />- <Input type="datetime-local" value={endsAt} onChange={(event) => setEndsAt(event.target.value)} aria-label="End date and time" />+ <div className="grid grid-cols-[24px_minmax(0,1fr)] items-center gap-3">+ <UsersRound aria-hidden="true" className="h-5 w-5 text-neutral-600" />+ <Input value={guests} onChange={(event) => setGuests(event.target.value)} placeholder="Add guests" aria-label="Guests (comma-separated emails)" className={eventFieldClass} />+ </div>+ <div className="grid grid-cols-[24px_minmax(0,1fr)] items-center gap-3">+ <MapPin aria-hidden="true" className="h-5 w-5 text-neutral-600" />+ <Input value={location} onChange={(event) => setLocation(event.target.value)} placeholder="Add location" aria-label="Location" className={eventFieldClass} />+ </div>+ <div className="grid grid-cols-[24px_minmax(0,1fr)] items-start gap-3">+ <AlignLeft aria-hidden="true" className="mt-2 h-5 w-5 text-neutral-600" />+ <Textarea value={description} onChange={(event) => setDescription(event.target.value)} placeholder="Add description" aria-label="Description" rows={1} className="min-h-9 resize-none border-transparent bg-transparent px-2 py-2 shadow-none hover:bg-white/60 focus:min-h-24 focus:resize-y focus:border-blue-600 focus:bg-white focus-visible:ring-0" />+ </div>+ <div className="grid grid-cols-[24px_minmax(0,1fr)] items-center gap-3">+ <Palette aria-hidden="true" className="h-5 w-5 text-neutral-600" />+ <div role="radiogroup" aria-label="Event color" className="flex flex-wrap items-center gap-1.5 px-2">+ {FOLDER_COLOR_OPTIONS.map((option) => (+ <button key={option.value} type="button" role="radio" aria-label={option.label} title={option.label} aria-checked={color === option.value} onClick={() => setColor(option.value)}+ className={`h-7 w-7 rounded-full border-2 transition-transform hover:scale-110 ${color === option.value ? "border-neutral-900 ring-2 ring-neutral-300 ring-offset-2" : "border-transparent"}`}+ style={{ backgroundColor: option.value }} />+ ))}+ </div></div>- <div className="mt-2 flex justify-between gap-2">- <div>{editing && <Button variant="ghost" disabled={pendingAction !== null} onClick={() => void deleteEvent(editing.id)} className="text-red-600 hover:bg-red-50"><Trash2 className="h-4 w-4" />Delete</Button>}</div>- <div className="flex gap-2">- <Button variant="ghost" disabled={pendingAction === "save"} onClick={() => { setEditing(null); setAdding(false); }}>Cancel</Button>- <Button onClick={() => void addEvent()} disabled={!title || !startsAt || !endsAt || new Date(endsAt) <= new Date(startsAt) || pendingAction === "save"}>- {pendingAction === "save" ? "Saving..." : editing ? "Save changes" : "Create event"}+ <div className="grid grid-cols-[24px_minmax(0,1fr)] gap-3 pt-6">+ <div />+ <div className="flex justify-between gap-2">+ <div>{editing && <Button variant="ghost" disabled={pendingAction !== null} onClick={() => void deleteEvent(editing.id)} className="px-2 text-red-600 hover:bg-red-50"><Trash2 className="h-4 w-4" />Delete</Button>}</div>+ <Button onClick={() => void addEvent()} disabled={!title.trim() || !startsAt || !endsAt || new Date(endsAt) <= new Date(startsAt) || (repeat === "weekdays" && repeatDays.length === 0) || pendingAction === "save"} className="rounded-full bg-blue-600 px-6 text-white hover:bg-blue-700">+ {pendingAction === "save" ? "Saving..." : "Save"}</Button></div></div>diff --git a/src/app/(dashboard)/calendar/types.d.ts b/src/app/(dashboard)/calendar/types.d.tsindex 2990663..30c5d51 100644--- a/src/app/(dashboard)/calendar/types.d.ts+++ b/src/app/(dashboard)/calendar/types.d.ts@@ -1,3 +1,5 @@+import type { CalendarRepeat } from "@/lib/calendar/types";+export type CalendarEvent = {id: string;title: string;@@ -7,6 +9,12 @@ export type CalendarEvent = {location: string;attendees: string;color: string;+ repeat: CalendarRepeat;+ repeatDays: string;+ repeatAnchorDay: number | null;+ repeatUntil: string | null;+ excludedOccurrences: string;+ seriesStartsAt?: string;};export type CalendarView = "week" | "day";diff --git a/src/app/(dashboard)/calendar/utils.ts b/src/app/(dashboard)/calendar/utils.tsindex 19d8ed9..46b74a0 100644--- a/src/app/(dashboard)/calendar/utils.ts+++ b/src/app/(dashboard)/calendar/utils.ts@@ -1,24 +1,85 @@import type { CalendarEvent, EventGroup, EventResizeEdge } from "./types";+import type { FolderColor } from "@/lib/folders/types";+import type { CalendarRepeat } from "@/lib/calendar/types";+import { parseCalendarRepeatDays, parseExcludedOccurrences } from "@/lib/calendar/recurrence";export const CALENDAR_START_HOUR = 0;export const CALENDAR_END_HOUR = 24;export const CALENDAR_HOUR_HEIGHT = 36;+export const UPCOMING_BATCH_SIZE = 14;+export const WEEKDAY_OPTIONS = [+ { value: 0, label: "Sun" }, { value: 1, label: "Mon" }, { value: 2, label: "Tue" },+ { value: 3, label: "Wed" }, { value: 4, label: "Thu" }, { value: 5, label: "Fri" },+ { value: 6, label: "Sat" },+] as const;++export const EVENT_COLOR_CLASSES: Record<FolderColor, string> = {+ "#2563eb": "bg-blue-600 text-white",+ "#7c3aed": "bg-violet-600 text-white",+ "#db2777": "bg-pink-600 text-white",+ "#dc2626": "bg-red-600 text-white",+ "#ea580c": "bg-orange-600 text-white",+ "#d97706": "bg-amber-600 text-white",+ "#16a34a": "bg-green-600 text-white",+ "#0d9488": "bg-teal-600 text-white",+};++export const PAST_EVENT_COLOR_CLASSES: Record<FolderColor, string> = {+ "#2563eb": "bg-blue-200 text-blue-900",+ "#7c3aed": "bg-violet-200 text-violet-900",+ "#db2777": "bg-pink-200 text-pink-900",+ "#dc2626": "bg-red-200 text-red-900",+ "#ea580c": "bg-orange-200 text-orange-900",+ "#d97706": "bg-amber-200 text-amber-900",+ "#16a34a": "bg-green-200 text-green-900",+ "#0d9488": "bg-teal-200 text-teal-900",+};++function recurringStart(first: Date, repeat: CalendarRepeat, index: number, anchorDay = first.getDate()): Date {+ if (repeat === "monthly") {+ const monthStart = new Date(first.getFullYear(), first.getMonth() + index, 1);+ const lastDay = new Date(monthStart.getFullYear(), monthStart.getMonth() + 1, 0).getDate();+ return new Date(monthStart.getFullYear(), monthStart.getMonth(), Math.min(anchorDay, lastDay), first.getHours(), first.getMinutes(), first.getSeconds(), first.getMilliseconds());+ }+ return new Date(first.getFullYear(), first.getMonth(), first.getDate() + index * (repeat === "weekly" ? 7 : 1), first.getHours(), first.getMinutes(), first.getSeconds(), first.getMilliseconds());+}++export function expandCalendarEvents(events: CalendarEvent[], rangeStart: Date, rangeEnd: Date): CalendarEvent[] {+ const occurrences: CalendarEvent[] = [];+ for (const event of events) {+ const first = new Date(event.startsAt);+ const duration = new Date(event.endsAt).getTime() - first.getTime();+ if (event.repeat === "none") {+ if (first < rangeEnd && first.getTime() + duration > rangeStart.getTime()) occurrences.push(event);+ continue;+ }+ const until = event.repeatUntil ? new Date(event.repeatUntil).getTime() : Infinity;+ const repeatDays = parseCalendarRepeatDays(event.repeatDays);+ const excluded = new Set(parseExcludedOccurrences(event.excludedOccurrences));+ for (let index = 0; index < 20_000; index++) {+ const startsAt = recurringStart(first, event.repeat, index, event.repeatAnchorDay ?? first.getDate());+ if (startsAt >= rangeEnd || startsAt.getTime() >= until) break;+ if (excluded.has(startsAt.getTime()) || (event.repeat === "weekdays" && !repeatDays.includes(startsAt.getDay()))) continue;+ const endsAt = new Date(startsAt.getTime() + duration);+ if (endsAt > rangeStart) occurrences.push({ ...event, id: `${event.id}@${startsAt.getTime()}`, seriesStartsAt: event.startsAt, startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString() });+ }+ }+ return occurrences.sort((a, b) => a.startsAt.localeCompare(b.startsAt));+}-export const EVENT_COLORS = {- blue: "border-blue-500 bg-blue-100 text-blue-900",- violet: "border-violet-500 bg-violet-100 text-violet-900",- emerald: "border-emerald-500 bg-emerald-100 text-emerald-900",- orange: "border-orange-500 bg-orange-100 text-orange-900",- rose: "border-rose-500 bg-rose-100 text-rose-900",-} as const;--export const EVENT_COLOR_DOTS = {- blue: "bg-blue-500",- violet: "bg-violet-500",- emerald: "bg-emerald-500",- orange: "bg-orange-500",- rose: "bg-rose-500",-} as const;+export function nextCalendarOccurrence(event: CalendarEvent, after: Date): Date | null {+ const first = new Date(event.seriesStartsAt ?? event.startsAt);+ const until = event.repeatUntil ? new Date(event.repeatUntil).getTime() : Infinity;+ const repeatDays = parseCalendarRepeatDays(event.repeatDays);+ const excluded = new Set(parseExcludedOccurrences(event.excludedOccurrences));+ for (let index = 0; index < 20_000; index++) {+ const startsAt = recurringStart(first, event.repeat, index, event.repeatAnchorDay ?? first.getDate());+ if (startsAt.getTime() >= until) return null;+ if (startsAt < after || excluded.has(startsAt.getTime()) || (event.repeat === "weekdays" && !repeatDays.includes(startsAt.getDay()))) continue;+ return startsAt;+ }+ return null;+}export function startOfDay(value: Date): Date {return new Date(value.getFullYear(), value.getMonth(), value.getDate());@@ -34,9 +95,8 @@ export function monthGridDates(month: Date): Date[] {return Array.from({ length: 42 }, (_, index) => addDays(gridStart, index));}-export function startOfWorkweek(value: Date): Date {- const day = value.getDay();- return addDays(startOfDay(value), day === 0 ? -6 : 1 - day);+export function startOfWeek(value: Date): Date {+ return addDays(startOfDay(value), -value.getDay());}export function dateKey(value: Date): string {@@ -47,6 +107,16 @@ export function formatLocalDateTime(value: Date): string {return `${dateKey(value)}T${String(value.getHours()).padStart(2, "0")}:${String(value.getMinutes()).padStart(2, "0")}`;}+export function eventEndAfterMinutes(start: string, minutes: number): string {+ const startDate = new Date(start);+ if (Number.isNaN(startDate.getTime())) return "";+ return formatLocalDateTime(new Date(startDate.getTime() + minutes * 60_000));+}++export function currentTimePosition(value: Date): number {+ return ((value.getHours() - CALENDAR_START_HOUR) * 60 + value.getMinutes() + value.getSeconds() / 60) * CALENDAR_HOUR_HEIGHT / 60;+}+export function formatHour(hour: number): string {return new Date(2026, 0, 1, hour).toLocaleTimeString(undefined, { hour: "numeric" });}@@ -83,6 +153,18 @@ export function groupUpcomingEvents(events: CalendarEvent[], today: Date): Eventreturn groups;}+export function takeUpcomingGroups(groups: EventGroup[], count: number): EventGroup[] {+ const visible: EventGroup[] = [];+ let remaining = count;+ for (const group of groups) {+ if (remaining <= 0) break;+ const events = group.events.slice(0, remaining);+ if (events.length) visible.push({ ...group, events });+ remaining -= events.length;+ }+ return visible;+}+export function eventPosition(event: CalendarEvent, day: Date): { top: number; height: number } | null {const start = new Date(event.startsAt);const end = new Date(event.endsAt);diff --git a/src/app/api/calendar/events/[eventId]/route.ts b/src/app/api/calendar/events/[eventId]/route.tsindex 37dd871..a02302e 100644--- a/src/app/api/calendar/events/[eventId]/route.ts+++ b/src/app/api/calendar/events/[eventId]/route.ts@@ -8,23 +8,52 @@ import { createCalendarInvitation } from "@/lib/calendar/utils";import { sendEmail } from "@/lib/email/send";import type { CalendarEventInput } from "../types";import type { CalendarEventRouteParams } from "./types";-import { normalizeCalendarColor } from "../utils";+import { normalizeCalendarColor } from "@/lib/calendar/colors";+import { DEFAULT_REPEAT_DAYS, normalizeCalendarRepeat, normalizeCalendarRepeatDays, parseCalendarOccurrenceId, parseCalendarRepeatDays, parseExcludedOccurrences } from "@/lib/calendar/recurrence";+import { newId } from "@/lib/ids";export async function PATCH(request: Request, { params }: CalendarEventRouteParams) {const env = getEnv();const user = await requireUser(env, request);const { eventId } = await params;+ const occurrence = parseCalendarOccurrenceId(eventId);const input = await request.json() as CalendarEventInput;const startsAt = new Date(input.startsAt);const endsAt = new Date(input.endsAt);+ const effectiveFrom = input.effectiveFrom ? new Date(input.effectiveFrom) : occurrence?.startsAt;if (!input.title?.trim() || Number.isNaN(startsAt.getTime()) || Number.isNaN(endsAt.getTime()) || endsAt <= startsAt) return NextResponse.json({ error: "Enter a title and valid event times" }, { status: 400 });+ if (effectiveFrom && Number.isNaN(effectiveFrom.getTime())) return NextResponse.json({ error: "Invalid repeat start" }, { status: 400 });const db = getDb(env);- const [existing] = await db.select().from(calendarEvents).where(and(eq(calendarEvents.id, eventId), eq(calendarEvents.userId, user.id))).limit(1);+ const [existing] = await db.select().from(calendarEvents).where(and(eq(calendarEvents.id, occurrence?.seriesId ?? eventId), eq(calendarEvents.userId, user.id))).limit(1);if (!existing) return NextResponse.json({ error: "Event not found" }, { status: 404 });+ if (occurrence && (existing.repeat === "none" || occurrence.startsAt < existing.startsAt || (existing.repeatUntil && occurrence.startsAt >= existing.repeatUntil))) return NextResponse.json({ error: "Occurrence not found" }, { status: 404 });+ if (existing.repeat !== "none" && effectiveFrom && existing.repeatUntil && effectiveFrom >= existing.repeatUntil) return NextResponse.json({ error: "No future occurrences remain" }, { status: 404 });const attendees = (input.attendees ?? []).map((email) => email.trim()).filter((email) => /^\S+@\S+\.\S+$/.test(email));- const event = { ...existing, title: input.title.trim(), description: input.description?.trim() ?? "", location: input.location?.trim() ?? "", attendees: JSON.stringify(attendees), color: normalizeCalendarColor(input.color ?? existing.color), startsAt, endsAt };- await db.update(calendarEvents).set({ title: event.title, description: event.description, location: event.location, attendees: event.attendees, color: event.color, startsAt, endsAt, updatedAt: new Date() }).where(eq(calendarEvents.id, eventId));- if (attendees.length && existing.mailboxId && input.from) { const file = createCalendarInvitation({ ...event, uid: eventId }); await Promise.all(attendees.map((to) => sendEmail(env, { userId: user.id, mailboxId: existing.mailboxId!, from: input.from!, to, subject: `Updated invitation: ${event.title}`, text: event.description || `This event has been updated: ${event.title}.`, attachments: [{ filename: "invite.ics", type: "text/calendar; charset=utf-8", content: file }] }))); }+ if (input.moveOccurrenceToPast) {+ if (!occurrence || existing.repeat === "none" || startsAt >= new Date()) return NextResponse.json({ error: "Choose a past time for this occurrence" }, { status: 400 });+ const excluded = parseExcludedOccurrences(existing.excludedOccurrences);+ if (excluded.includes(occurrence.startsAt.getTime())) return NextResponse.json({ error: "Occurrence already moved" }, { status: 409 });+ const now = new Date();+ const moved = { ...existing, id: newId("evt"), title: input.title.trim(), description: input.description?.trim() ?? "", location: input.location?.trim() ?? "", attendees: JSON.stringify(attendees), color: normalizeCalendarColor(input.color ?? existing.color), repeat: "none" as const, repeatDays: "[]", repeatAnchorDay: null, repeatUntil: null, excludedOccurrences: "[]", startsAt, endsAt, createdAt: now, updatedAt: now };+ await db.insert(calendarEvents).values(moved);+ await db.update(calendarEvents).set({ excludedOccurrences: JSON.stringify([...excluded, occurrence.startsAt.getTime()]), updatedAt: now }).where(eq(calendarEvents.id, existing.id));+ if (attendees.length && existing.mailboxId && input.from) { const file = createCalendarInvitation({ ...moved, uid: moved.id }); await Promise.all(attendees.map((to) => sendEmail(env, { userId: user.id, mailboxId: existing.mailboxId!, from: input.from!, to, subject: `Updated invitation: ${moved.title}`, text: moved.description || `This event has been updated: ${moved.title}.`, attachments: [{ filename: "invite.ics", type: "text/calendar; charset=utf-8", content: file }] }))); }+ return NextResponse.json({ ok: true });+ }+ const repeat = normalizeCalendarRepeat(input.repeat ?? existing.repeat);+ const repeatDays = repeat === "weekdays" ? normalizeCalendarRepeatDays(input.repeatDays ?? (existing.repeat === "weekdays" ? parseCalendarRepeatDays(existing.repeatDays) : DEFAULT_REPEAT_DAYS)) : [];+ if (repeat === "weekdays" && repeatDays.length === 0) return NextResponse.json({ error: "Choose at least one weekday" }, { status: 400 });+ const repeatAnchorDay = repeat === "monthly" && Number.isInteger(input.repeatAnchorDay) && input.repeatAnchorDay! >= 1 && input.repeatAnchorDay! <= 31 ? input.repeatAnchorDay : repeat === "monthly" ? existing.repeatAnchorDay : null;+ const event = { ...existing, title: input.title.trim(), description: input.description?.trim() ?? "", location: input.location?.trim() ?? "", attendees: JSON.stringify(attendees), color: normalizeCalendarColor(input.color ?? existing.color), repeat, repeatDays: JSON.stringify(repeatDays), repeatAnchorDay, repeatUntil: repeat === "none" ? null : existing.repeatUntil, startsAt, endsAt };+ const splitAt = existing.repeat !== "none" ? effectiveFrom : null;+ if (splitAt && splitAt > existing.startsAt) {+ const now = new Date();+ await db.insert(calendarEvents).values({ ...event, id: newId("evt"), createdAt: now, updatedAt: now });+ await db.update(calendarEvents).set({ repeatUntil: splitAt, updatedAt: now }).where(eq(calendarEvents.id, existing.id));+ } else {+ await db.update(calendarEvents).set({ title: event.title, description: event.description, location: event.location, attendees: event.attendees, color: event.color, repeat: event.repeat, repeatDays: event.repeatDays, repeatAnchorDay: event.repeatAnchorDay, repeatUntil: event.repeatUntil, startsAt, endsAt, updatedAt: new Date() }).where(eq(calendarEvents.id, existing.id));+ }+ if (attendees.length && existing.mailboxId && input.from) { const file = createCalendarInvitation({ ...event, uid: existing.id }); await Promise.all(attendees.map((to) => sendEmail(env, { userId: user.id, mailboxId: existing.mailboxId!, from: input.from!, to, subject: `Updated invitation: ${event.title}`, text: event.description || `This event has been updated: ${event.title}.`, attachments: [{ filename: "invite.ics", type: "text/calendar; charset=utf-8", content: file }] }))); }return NextResponse.json({ ok: true });}@@ -32,6 +61,15 @@ export async function DELETE(_request: Request, { params }: CalendarEventRoutePaconst env = getEnv();const user = await requireUser(env, _request);const { eventId } = await params;- await getDb(env).delete(calendarEvents).where(and(eq(calendarEvents.id, eventId), eq(calendarEvents.userId, user.id)));+ const occurrence = parseCalendarOccurrenceId(eventId);+ const input = await _request.json().catch(() => ({})) as CalendarEventInput;+ const effectiveFrom = input.effectiveFrom ? new Date(input.effectiveFrom) : occurrence?.startsAt;+ if (effectiveFrom && Number.isNaN(effectiveFrom.getTime())) return NextResponse.json({ error: "Invalid repeat start" }, { status: 400 });+ const db = getDb(env);+ const [existing] = await db.select().from(calendarEvents).where(and(eq(calendarEvents.id, occurrence?.seriesId ?? eventId), eq(calendarEvents.userId, user.id))).limit(1);+ if (!existing) return NextResponse.json({ error: "Event not found" }, { status: 404 });+ if (occurrence && (existing.repeat === "none" || occurrence.startsAt < existing.startsAt || (existing.repeatUntil && occurrence.startsAt >= existing.repeatUntil))) return NextResponse.json({ error: "Occurrence not found" }, { status: 404 });+ if (existing.repeat !== "none" && effectiveFrom && effectiveFrom > existing.startsAt) await db.update(calendarEvents).set({ repeatUntil: effectiveFrom, updatedAt: new Date() }).where(eq(calendarEvents.id, existing.id));+ else await db.delete(calendarEvents).where(eq(calendarEvents.id, existing.id));return NextResponse.json({ ok: true });}diff --git a/src/app/api/calendar/events/route.ts b/src/app/api/calendar/events/route.tsindex 9fe8573..45d0581 100644--- a/src/app/api/calendar/events/route.ts+++ b/src/app/api/calendar/events/route.ts@@ -1,4 +1,4 @@-import { and, eq, gte, lt } from "drizzle-orm";+import { and, eq, gte, lt, ne, or } from "drizzle-orm";import { NextResponse } from "next/server";import { getDb } from "@/db";import { calendarEvents } from "@/db/schema";@@ -7,8 +7,9 @@ import { getEnv } from "@/lib/cloudflare";import { newId } from "@/lib/ids";import { sendEmail } from "@/lib/email/send";import { createCalendarInvitation } from "@/lib/calendar/utils";+import { normalizeCalendarColor } from "@/lib/calendar/colors";+import { DEFAULT_REPEAT_DAYS, normalizeCalendarRepeat, normalizeCalendarRepeatDays } from "@/lib/calendar/recurrence";import type { CalendarEventInput } from "./types";-import { normalizeCalendarColor } from "./utils";export async function GET(request: Request) {const env = getEnv();@@ -16,7 +17,7 @@ export async function GET(request: Request) {const url = new URL(request.url);const start = new Date(url.searchParams.get("start") ?? Date.now());const end = new Date(url.searchParams.get("end") ?? start.getTime() + 31 * 86_400_000);- const events = await getDb(env).select().from(calendarEvents).where(and(eq(calendarEvents.userId, user.id), gte(calendarEvents.startsAt, start), lt(calendarEvents.startsAt, end))).orderBy(calendarEvents.startsAt);+ const events = await getDb(env).select().from(calendarEvents).where(and(eq(calendarEvents.userId, user.id), lt(calendarEvents.startsAt, end), or(gte(calendarEvents.endsAt, start), ne(calendarEvents.repeat, "none")))).orderBy(calendarEvents.startsAt);return NextResponse.json({ events });}@@ -27,8 +28,11 @@ export async function POST(request: Request) {const startsAt = new Date(input.startsAt);const endsAt = new Date(input.endsAt);if (!input.title?.trim() || Number.isNaN(startsAt.getTime()) || Number.isNaN(endsAt.getTime()) || endsAt <= startsAt) return NextResponse.json({ error: "Enter a title and valid event times" }, { status: 400 });+ const repeat = normalizeCalendarRepeat(input.repeat);+ const repeatDays = repeat === "weekdays" ? normalizeCalendarRepeatDays(input.repeatDays ?? DEFAULT_REPEAT_DAYS) : [];+ if (repeat === "weekdays" && repeatDays.length === 0) return NextResponse.json({ error: "Choose at least one weekday" }, { status: 400 });const attendees = (input.attendees ?? []).map((email) => email.trim()).filter((email) => /^\S+@\S+\.\S+$/.test(email));- const event = { id: newId("evt"), userId: user.id, mailboxId: input.mailboxId ?? null, title: input.title.trim(), description: input.description?.trim() ?? "", location: input.location?.trim() ?? "", attendees: JSON.stringify(attendees), color: normalizeCalendarColor(input.color), startsAt, endsAt };+ const event = { id: newId("evt"), userId: user.id, mailboxId: input.mailboxId ?? null, title: input.title.trim(), description: input.description?.trim() ?? "", location: input.location?.trim() ?? "", attendees: JSON.stringify(attendees), color: normalizeCalendarColor(input.color), repeat, repeatDays: JSON.stringify(repeatDays), repeatAnchorDay: repeat === "monthly" && Number.isInteger(input.repeatAnchorDay) && input.repeatAnchorDay! >= 1 && input.repeatAnchorDay! <= 31 ? input.repeatAnchorDay : null, startsAt, endsAt };await getDb(env).insert(calendarEvents).values(event);if (attendees.length && input.mailboxId) {const calendarFile = createCalendarInvitation({ ...event, uid: event.id });diff --git a/src/app/api/calendar/events/types.d.ts b/src/app/api/calendar/events/types.d.tsindex d17d6bc..75f667a 100644--- a/src/app/api/calendar/events/types.d.ts+++ b/src/app/api/calendar/events/types.d.ts@@ -1,9 +1,16 @@+import type { CalendarRepeat } from "@/lib/calendar/types";+export type CalendarEventInput = {title: string;description?: string;location?: string;attendees?: string[];color?: string;+ repeat?: CalendarRepeat;+ repeatDays?: number[];+ repeatAnchorDay?: number;+ effectiveFrom?: string;+ moveOccurrenceToPast?: boolean;startsAt: string;endsAt: string;mailboxId?: string | null;diff --git a/src/app/api/calendar/events/utils.ts b/src/app/api/calendar/events/utils.tsdeleted file mode 100644index 80d58a8..0000000--- a/src/app/api/calendar/events/utils.ts+++ /dev/null@@ -1,5 +0,0 @@-export function normalizeCalendarColor(value: string | undefined): string {- return value && ["blue", "violet", "emerald", "orange", "rose"].includes(value)- ? value- : "blue";-}diff --git a/src/components/components-nav.tsx b/src/components/components-nav.tsxindex 135aa39..acc7f7f 100644--- a/src/components/components-nav.tsx+++ b/src/components/components-nav.tsx@@ -80,7 +80,7 @@ export function NavItem({ link }: { link: NavLink }) {size={21}style={{ color: link.iconColor }}/>- {!minimal && <span className={cn("flex-1", typeof link.count === "number" && link.count > 0 && "font-bold")}>{link.label}</span>}+ {!minimal && <span className={cn("flex-1", typeof link.count === "number" && link.count > 0 && "font-semibold")}>{link.label}</span>}{!minimal && typeof link.count === "number" && link.count > 0 && (<span className="ml-auto mr-3 rounded-full px-2 py-0.5 text-sm font-semibold text-neutral-700">{link.count > 99 ? "99+" : link.count}@@ -142,7 +142,7 @@ export function NavItem({ link }: { link: NavLink }) {style={{ color: link.iconColor }}size={18}/>- {!minimal && <span className={cn("flex-1", typeof link.count === "number" && link.count > 0 && "font-bold")}>{link.label}</span>}+ {!minimal && <span className={cn("flex-1", typeof link.count === "number" && link.count > 0 && "font-semibold")}>{link.label}</span>}{!minimal && typeof link.count === "number" && link.count > 0 && (<span className="ml-auto mr-3 rounded-full px-2 py-0.5 text-sm font-semibold text-neutral-700">{link.count > 99 ? "99+" : link.count}diff --git a/src/components/mailbox-selector.tsx b/src/components/mailbox-selector.tsxindex 0a572d4..36aed6f 100644--- a/src/components/mailbox-selector.tsx+++ b/src/components/mailbox-selector.tsx@@ -2,7 +2,7 @@import Link from "next/link";import { usePathname, useRouter } from "next/navigation";-import { CalendarDays, Check, LogOut, Settings, ShieldCheck, UserRound, UsersRound } from "lucide-react";+import { CalendarDays, Check, Inbox, LogOut, Settings, ShieldCheck, UserRound, UsersRound } from "lucide-react";import { useEffect, useRef, useState } from "react";import { useSelectedMailbox } from "@/components/mailbox-provider";import { ProgressiveAvatarImage } from "@/components/progressive-avatar-image";@@ -265,9 +265,17 @@ export function MailboxSelector({ initialUser }: MailboxSelectorProps = {}) {<Check className="h-5 w-5 shrink-0 text-blue-600" /></div><Link- href="/calendar"+ href="/inbox"onClick={() => setOpen(false)}className="mt-4 flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-[#f2f6fc]"+ >+ <Inbox className="h-5 w-5 text-neutral-600" />+ Inbox+ </Link>+ <Link+ href="/calendar"+ onClick={() => setOpen(false)}+ className="mt-1 flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-[#f2f6fc]"><CalendarDays className="h-5 w-5 text-neutral-600" />Calendar@@ -298,6 +306,7 @@ export function MailboxSelector({ initialUser }: MailboxSelectorProps = {}) {onSelect={() => {setSelectedMailbox(mailbox);setOpen(false);+ router.push("/inbox");}}/>);diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex 0dfc774..ee1a69e 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -381,6 +381,11 @@ export const calendarEvents = sqliteTable(location: text("location").notNull().default(""),attendees: text("attendees").notNull().default("[]"),color: text("color").notNull().default("blue"),+ repeat: text("repeat", { enum: ["none", "daily", "weekly", "monthly", "weekdays"] }).notNull().default("none"),+ repeatDays: text("repeat_days").notNull().default("[]"),+ repeatAnchorDay: integer("repeat_anchor_day"),+ repeatUntil: integer("repeat_until", { mode: "timestamp" }),+ excludedOccurrences: text("excluded_occurrences").notNull().default("[]"),startsAt: integer("starts_at", { mode: "timestamp" }).notNull(),endsAt: integer("ends_at", { mode: "timestamp" }).notNull(),createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),diff --git a/src/lib/calendar/colors.ts b/src/lib/calendar/colors.tsnew file mode 100644index 0000000..b2772aa--- /dev/null+++ b/src/lib/calendar/colors.ts@@ -0,0 +1,16 @@+import { DEFAULT_FOLDER_COLOR, FOLDER_COLOR_VALUES } from "@/lib/folders/colors";+import type { FolderColor } from "@/lib/folders/types";++const LEGACY_CALENDAR_COLORS: Record<string, FolderColor> = {+ blue: "#2563eb",+ violet: "#7c3aed",+ rose: "#db2777",+ orange: "#ea580c",+ emerald: "#16a34a",+};++export function normalizeCalendarColor(value: string | undefined): FolderColor {+ return FOLDER_COLOR_VALUES.find((color) => color === value)+ ?? LEGACY_CALENDAR_COLORS[value ?? ""]+ ?? DEFAULT_FOLDER_COLOR;+}diff --git a/src/lib/calendar/recurrence.ts b/src/lib/calendar/recurrence.tsnew file mode 100644index 0000000..f19959c--- /dev/null+++ b/src/lib/calendar/recurrence.ts@@ -0,0 +1,32 @@+import type { CalendarRepeat } from "./types";++export const DEFAULT_REPEAT_DAYS = [1, 2, 3, 4, 5];++export function normalizeCalendarRepeat(value: string | undefined): CalendarRepeat {+ return value === "daily" || value === "weekly" || value === "monthly" || value === "weekdays" ? value : "none";+}++export function normalizeCalendarRepeatDays(value: unknown): number[] {+ return Array.isArray(value)+ ? [...new Set(value.filter((day): day is number => Number.isInteger(day) && day >= 0 && day <= 6))].sort((a, b) => a - b)+ : [];+}++export function parseCalendarRepeatDays(value: string | undefined): number[] {+ try { return normalizeCalendarRepeatDays(JSON.parse(value ?? "[]")); } catch { return []; }+}++export function parseExcludedOccurrences(value: string | undefined): number[] {+ try {+ const parsed: unknown = JSON.parse(value ?? "[]");+ return Array.isArray(parsed) ? parsed.filter((timestamp): timestamp is number => Number.isSafeInteger(timestamp) && timestamp >= 0) : [];+ } catch { return []; }+}++export function parseCalendarOccurrenceId(value: string): { seriesId: string; startsAt: Date } | null {+ const separator = value.lastIndexOf("@");+ if (separator < 1) return null;+ const timestamp = Number(value.slice(separator + 1));+ if (!Number.isSafeInteger(timestamp) || timestamp < 0) return null;+ return { seriesId: value.slice(0, separator), startsAt: new Date(timestamp) };+}diff --git a/src/lib/calendar/types.d.ts b/src/lib/calendar/types.d.tsnew file mode 100644index 0000000..15fa50f--- /dev/null+++ b/src/lib/calendar/types.d.ts@@ -0,0 +1 @@+export type CalendarRepeat = "none" | "daily" | "weekly" | "monthly" | "weekdays";