Skip to content

Your favorite shift management application!

feat(ui): month, week and list calendar views (#213)

panteL006cee7f50ff
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index ea5ab48..0ab56b8 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -63,6 +63,8 @@ export async function GET(request: Request) {
signupCapacity: shifts.signupCapacity,
syncedFromExternal: shifts.syncedFromExternal,
externalSyncId: shifts.externalSyncId,
+ // The list view's preset filter groups by this
+ presetId: shifts.presetId,
createdBy: shifts.createdBy,
createdAt: shifts.createdAt,
updatedAt: shifts.updatedAt,
diff --git a/app/page.tsx b/app/page.tsx
index 2782ce2..d726e61 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -3,7 +3,7 @@
import { useState, useEffect, Suspense, useCallback, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
-import { isSameMonth } from "date-fns";
+import { addDays, isSameMonth, isSameWeek, startOfWeek } from "date-fns";
import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote } from "@/lib/db/schema";
import { useCalendars } from "@/hooks/useCalendars";
@@ -22,6 +22,7 @@ import { useAuth } from "@/hooks/useAuth";
import { useConnectionStatus } from "@/hooks/useConnectionStatus";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { CalendarViewMode, useCalendarViewMode } from "@/hooks/useCalendarViewMode";
import { EmptyCalendarState } from "@/components/empty-calendar-state";
import { GuestEmptyState } from "@/components/guest-empty-state";
import { FullscreenLoader } from "@/components/fullscreen-loader";
@@ -31,7 +32,7 @@ import { CalendarWorkspace } from "@/components/calendar-workspace";
import { AppHeader } from "@/components/app-header";
import { DialogManager } from "@/components/dialog-manager";
import { ShiftFormData } from "@/components/shift-sheet";
-import { getCalendarDays } from "@/lib/calendar-utils";
+import { getCalendarDays, getMonthDays, getWeekDays } from "@/lib/calendar-utils";
import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
import { findNotesForDate } from "@/lib/event-utils";
import { DayLayoutOptions } from "@/lib/shift-display";
@@ -156,6 +157,10 @@ function HomeContent() {
selectedPresetIds,
});
+ const [storedViewMode, setViewMode] = useCalendarViewMode();
+ // Compare mode shares one month grid, whatever this device last used
+ const viewMode: CalendarViewMode = isCompareMode ? "month" : storedViewMode;
+
const {
notes,
createNote: createNoteHook,
@@ -288,14 +293,31 @@ function HomeContent() {
refetchShifts();
};
- // Month navigation keeps the selection inside the visible month
+ // Navigation keeps the selection inside the visible period
const handleDateChange = (date: Date) => {
setCurrentDate(date);
+ if (viewMode === "week") {
+ if (!isSameWeek(selectedDay, date, { weekStartsOn: 1 })) {
+ const now = new Date();
+ selectDay(
+ isSameWeek(now, date, { weekStartsOn: 1 })
+ ? now
+ : addDays(startOfWeek(date, { weekStartsOn: 1 }), (selectedDay.getDay() + 6) % 7)
+ );
+ }
+ return;
+ }
if (!isSameMonth(selectedDay, date)) {
selectDay(isSameMonth(new Date(), date) ? new Date() : new Date(date.getFullYear(), date.getMonth(), 1));
}
};
+ const handleViewModeChange = (mode: CalendarViewMode) => {
+ // Week anchors on the focused day; leaving week re-anchors on it when the two drifted apart
+ if (!isSameMonth(selectedDay, currentDate) || mode === "week") setCurrentDate(selectedDay);
+ setViewMode(mode);
+ };
+
// Compare mode shares one grid, so it always uses the personal view
const personalView = viewSettings.personal;
const calendarView = viewSettings.forCalendar(
@@ -366,14 +388,10 @@ function HomeContent() {
onDeleteNoteFromList={handleDeleteNoteFromList}
onAddNewNote={handleAddNewNoteFromList}
currentDate={currentDate}
- shifts={shifts}
canEditShift={canEditShift}
canDeleteShift={canDeleteShift}
showMonthStatsDialog={dialogStates.showMonthStatsDialog}
onMonthStatsDialogChange={dialogStates.setShowMonthStatsDialog}
- showMonthShiftsDialog={dialogStates.showMonthShiftsDialog}
- onMonthShiftsDialogChange={dialogStates.setShowMonthShiftsDialog}
- onDeleteShift={(shift) => shiftActions.handleDeleteShift(shift.id)}
showPresetManageDialog={dialogStates.showPresetManageDialog}
onPresetManageDialogChange={dialogStates.setShowPresetManageDialog}
/>
@@ -390,7 +408,15 @@ function HomeContent() {
/>
);
- const calendarDays = useMemo(() => getCalendarDays(currentDate), [currentDate]);
+ const calendarDays = useMemo(
+ () =>
+ viewMode === "week"
+ ? getWeekDays(currentDate)
+ : viewMode === "list"
+ ? getMonthDays(currentDate)
+ : getCalendarDays(currentDate),
+ [currentDate, viewMode]
+ );
if (
(!hasLoadedOnce && loading) ||
@@ -477,6 +503,8 @@ function HomeContent() {
onSyncNotifications={() => dialogStates.setShowSyncNotificationDialog(true)}
onCompare={openComparePicker}
onViewSettings={() => dialogStates.setShowViewSettingsDialog(true)}
+ viewMode={viewMode}
+ onViewModeChange={handleViewModeChange}
/>
);
@@ -490,8 +518,15 @@ function HomeContent() {
calendarDays={calendarDays}
currentDate={currentDate}
onDateChange={handleDateChange}
+ viewMode={viewMode}
+ onViewModeChange={handleViewModeChange}
selectedDay={selectedDay}
onDayClick={handleDayClick}
+ onSelectDay={(day) => {
+ // currentDate keys the month stats query, so only move it across months
+ if (!isSameMonth(day, currentDate)) setCurrentDate(day);
+ selectDay(day);
+ }}
onDayContextMenu={(date) => openNotesForDay(notes, date)}
shifts={shifts}
notes={notes}
@@ -499,6 +534,13 @@ function HomeContent() {
externalSyncs={externalSyncs}
togglingDates={shiftActions.togglingDates}
layout={toDayLayout(calendarView)}
+ listSort={{
+ type: calendarView.sortType,
+ order: calendarView.sortOrder,
+ // A calendar-pinned view replaces the personal one, so the personal sort is moot
+ locked: !!calendars.find((c) => c.id === selectedCalendar)?.viewSettings,
+ onChange: viewSettings.updatePersonal,
+ }}
showShiftNotes={calendarView.showShiftNotes}
highlightedWeekdays={calendarView.highlightedWeekdays}
highlightColor={calendarView.highlightColor}
@@ -522,7 +564,13 @@ function HomeContent() {
onAddNote: () => noteActions.openNoteDialog(selectedDay, undefined),
onOpenNote: (note) => noteActions.openNoteDialog(selectedDay, note),
onOpenStats: () => dialogStates.setShowMonthStatsDialog(true),
- onOpenMonthShifts: () => dialogStates.setShowMonthShiftsDialog(true),
+ onShowList:
+ viewMode === "list"
+ ? undefined
+ : () => {
+ setDaySheetOpen(false);
+ handleViewModeChange("list");
+ },
}}
/>
diff --git a/components/app-header.tsx b/components/app-header.tsx
index 02d9de6..372fede 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -3,7 +3,7 @@
import { useState } from "react";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
-import { addMonths, format, subMonths } from "date-fns";
+import { addMonths, addWeeks, getISOWeek } from "date-fns";
import {
Bell,
CalendarDays,
@@ -17,10 +17,12 @@ import { CalendarWithCount } from "@/lib/types";
import { CalendarSwitcher } from "@/components/calendar-switcher";
import { GuestMenu, UserMenu } from "@/components/user-menu";
import { InfoDialog } from "@/components/info-dialog";
+import { ViewModeSwitcher } from "@/components/view-mode-switcher";
import { useAuth } from "@/hooks/useAuth";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
-import { getDateLocale } from "@/lib/locales";
+import { CalendarViewMode } from "@/hooks/useCalendarViewMode";
+import { formatPeriodCaption, PeriodStep } from "@/lib/date-utils";
import { cn } from "@/lib/utils";
interface AppHeaderProps {
@@ -37,6 +39,13 @@ interface AppHeaderProps {
onSyncNotifications: () => void;
onCompare?: () => void;
onViewSettings?: () => void;
+ /** Absent in contexts without view modes; the switcher is then not rendered */
+ viewMode?: CalendarViewMode;
+ onViewModeChange?: (mode: CalendarViewMode) => void;
+}
+
+export function stepDate(date: Date, step: PeriodStep, direction: 1 | -1): Date {
+ return step === "week" ? addWeeks(date, direction) : addMonths(date, direction);
}
export function HeaderIconButton({
@@ -70,9 +79,11 @@ export function HeaderIconButton({
export function MonthArrows({
currentDate,
onDateChange,
+ step = "month",
}: {
currentDate: Date;
onDateChange: (date: Date) => void;
+ step?: PeriodStep;
}) {
const t = useTranslations();
const stepClass =
@@ -83,8 +94,8 @@ export function MonthArrows({
<button
type="button"
className={stepClass}
- onClick={() => onDateChange(subMonths(currentDate, 1))}
- aria-label={t("calendarView.previousMonth")}
+ onClick={() => onDateChange(stepDate(currentDate, step, -1))}
+ aria-label={step === "week" ? t("calendarView.previousWeek") : t("calendarView.previousMonth")}
>
<ChevronLeft className="size-[18px]" />
</button>
@@ -92,8 +103,8 @@ export function MonthArrows({
<button
type="button"
className={stepClass}
- onClick={() => onDateChange(addMonths(currentDate, 1))}
- aria-label={t("calendarView.nextMonth")}
+ onClick={() => onDateChange(stepDate(currentDate, step, 1))}
+ aria-label={step === "week" ? t("calendarView.nextWeek") : t("calendarView.nextMonth")}
>
<ChevronRight className="size-[18px]" />
</button>
@@ -158,10 +169,12 @@ export function MonthStepper({
currentDate,
onDateChange,
className,
+ step = "month",
}: {
currentDate: Date;
onDateChange: (date: Date) => void;
className?: string;
+ step?: PeriodStep;
}) {
const t = useTranslations();
const locale = useLocale();
@@ -173,19 +186,29 @@ export function MonthStepper({
<button
type="button"
className={stepClass}
- onClick={() => onDateChange(subMonths(currentDate, 1))}
- aria-label={t("calendarView.previousMonth")}
+ onClick={() => onDateChange(stepDate(currentDate, step, -1))}
+ aria-label={step === "week" ? t("calendarView.previousWeek") : t("calendarView.previousMonth")}
>
<ChevronLeft className="size-4" />
</button>
- <span className="min-w-[150px] text-center text-[15px] font-semibold text-fg-strong">
- {format(currentDate, "LLLL yyyy", { locale: getDateLocale(locale) })}
+ <span
+ className={cn(
+ "text-center text-[15px] font-semibold text-fg-strong",
+ step === "week" ? "min-w-[232px]" : "min-w-[150px]"
+ )}
+ >
+ {formatPeriodCaption(currentDate, step, locale)}
+ {step === "week" && (
+ <span className="ml-2 font-mono text-[12px] font-medium text-fg-tertiary">
+ {t("calendarView.calendarWeek", { week: getISOWeek(currentDate) })}
+ </span>
+ )}
</span>
<button
type="button"
className={stepClass}
- onClick={() => onDateChange(addMonths(currentDate, 1))}
- aria-label={t("calendarView.nextMonth")}
+ onClick={() => onDateChange(stepDate(currentDate, step, 1))}
+ aria-label={step === "week" ? t("calendarView.nextWeek") : t("calendarView.nextMonth")}
>
<ChevronRight className="size-4" />
</button>
@@ -206,6 +229,8 @@ export function AppHeader({
onSyncNotifications,
onCompare,
onViewSettings,
+ viewMode,
+ onViewModeChange,
}: AppHeaderProps) {
const t = useTranslations();
const locale = useLocale();
@@ -292,7 +317,14 @@ export function AppHeader({
onCompare={onCompare}
/>
<div className="h-6 w-px bg-line" />
- <MonthStepper currentDate={currentDate} onDateChange={onDateChange} />
+ <MonthStepper
+ currentDate={currentDate}
+ onDateChange={onDateChange}
+ step={viewMode === "week" ? "week" : "month"}
+ />
+ {viewMode && onViewModeChange && (
+ <ViewModeSwitcher value={viewMode} onChange={onViewModeChange} variant="text" />
+ )}
<div className="flex-1" />
{showUpdate && (
<UpdatePill
diff --git a/components/calendar-workspace.tsx b/components/calendar-workspace.tsx
index b34d2af..e8e81ec 100644
--- a/components/calendar-workspace.tsx
+++ b/components/calendar-workspace.tsx
@@ -2,27 +2,33 @@
import { useMemo, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
-import { format, startOfWeek } from "date-fns";
+import { startOfMonth, startOfWeek } from "date-fns";
import { RefreshCw, WifiOff } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
-import { MonthArrows } from "@/components/app-header";
+import { MonthArrows, stepDate } from "@/components/app-header";
import { MonthGrid } from "@/components/month-grid";
+import { WeekGrid } from "@/components/week-grid";
+import { ListSort, ShiftListView } from "@/components/shift-list-view";
import { DayInspector, DayActions, DayViewModel } from "@/components/day-inspector";
import { MobileDayFooter, MobileDaySheet, MobileStatsSheet } from "@/components/mobile-day-sheet";
import { MobilePresetBar, StampDock, orderStampPresets } from "@/components/stamp-dock";
import { GuestBanner } from "@/components/guest-banner";
import { ReadOnlyBanner } from "@/components/read-only-banner";
import { StatusBanner } from "@/components/status-banner";
+import { ViewModeSwitcher } from "@/components/view-mode-switcher";
import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
import { DayLayoutOptions } from "@/lib/shift-display";
-import { getDateLocale } from "@/lib/locales";
+import { formatDateToLocal, formatPeriodCaption } from "@/lib/date-utils";
+import { cn } from "@/lib/utils";
import { useDayData, usePeriodSummary, StatsPeriod } from "@/hooks/useDaySummary";
import { useStampShortcuts } from "@/hooks/useStampShortcuts";
+import { useSwipeNavigation } from "@/hooks/useSwipeNavigation";
import { useConnectionStatus } from "@/hooks/useConnectionStatus";
import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
import { useAuth } from "@/hooks/useAuth";
+import { CalendarViewMode } from "@/hooks/useCalendarViewMode";
interface CalendarWorkspaceProps {
header: React.ReactNode;
@@ -30,8 +36,12 @@ interface CalendarWorkspaceProps {
calendarDays: Date[];
currentDate: Date;
onDateChange: (date: Date) => void;
+ viewMode: CalendarViewMode;
+ onViewModeChange: (mode: CalendarViewMode) => void;
selectedDay: Date;
onDayClick: (date: Date) => void;
+ /** Pure navigation: shows the day's month and selects it, never stamps */
+ onSelectDay: (day: Date) => void;
onDayContextMenu: (date: Date) => void;
shifts: ShiftWithCalendar[];
notes: CalendarNote[];
@@ -39,6 +49,8 @@ interface CalendarWorkspaceProps {
externalSyncs: ExternalSync[];
togglingDates: Set<string>;
layout: DayLayoutOptions;
+ /** List view only: the personal sort, plus whether a calendar-pinned view locks it */
+ listSort: ListSort;
showShiftNotes: boolean;
highlightedWeekdays: number[];
highlightColor: string;
@@ -71,8 +83,11 @@ export function CalendarWorkspace({
calendarDays,
currentDate,
onDateChange,
+ viewMode,
+ onViewModeChange,
selectedDay,
onDayClick,
+ onSelectDay,
onDayContextMenu,
shifts,
notes,
@@ -80,6 +95,7 @@ export function CalendarWorkspace({
externalSyncs,
togglingDates,
layout,
+ listSort,
showShiftNotes,
highlightedWeekdays,
highlightColor,
@@ -106,6 +122,7 @@ export function CalendarWorkspace({
const { isOnline } = useConnectionStatus({ toasts: false });
const [period, setPeriod] = useState<StatsPeriod>("month");
const [statsOpen, setStatsOpen] = useState(false);
+ const [scrollTarget, setScrollTarget] = useState<{ key: string; nonce: number } | null>(null);
// Grid and day view only; stats stay on the full list so totals don't look broken
const visibleShifts = useMemo(() => {
@@ -113,6 +130,30 @@ export function CalendarWorkspace({
return shifts.filter((shift) => shift.signups?.some((s) => s.id === user.id));
}, [shifts, onlyMyShifts, user]);
+ // Own shifts only: imported calendars (holidays, colleagues) are not "my next shift"
+ const nextShift = useMemo(() => {
+ if (viewMode !== "list" || desktop) return null;
+ const now = new Date();
+ const todayKey = formatDateToLocal(now);
+ const nowTime = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
+ let best: { shift: ShiftWithCalendar; sortKey: string } | null = null;
+ for (const shift of visibleShifts) {
+ if (!shift.date || shift.syncedFromExternal) continue;
+ const dayKey = formatDateToLocal(shift.date as Date);
+ if (dayKey < todayKey) continue;
+ // Today's shifts that already ended are over; overnight ones (end < start) still count
+ const ended =
+ dayKey === todayKey &&
+ !shift.isAllDay &&
+ shift.endTime > shift.startTime &&
+ shift.endTime.slice(0, 5) <= nowTime;
+ if (ended) continue;
+ const sortKey = `${dayKey} ${shift.isAllDay ? "00:00" : shift.startTime}`;
+ if (!best || sortKey < best.sortKey) best = { shift, sortKey };
+ }
+ return best?.shift ?? null;
+ }, [viewMode, visibleShifts, desktop]);
+
// MobileStatsSheet is skip-mounted below when !canViewStats, so a lingering
// `true` here would pop it open unbidden if the capability comes back later.
// Adjusted during render (not an effect) per React's "adjusting state when a
@@ -124,21 +165,34 @@ export function CalendarWorkspace({
}
const dayData = useDayData({ selectedDay, shifts: visibleShifts, notes });
+ // First-of-month, not the exact day, so stepping through the month reuses one cache entry
+ const monthKey = `${currentDate.getFullYear()}-${currentDate.getMonth()}`;
+ const monthAnchor = useMemo(() => {
+ const [year, month] = monthKey.split("-").map(Number);
+ return startOfMonth(new Date(year, month, 1));
+ }, [monthKey]);
const monthSummary = usePeriodSummary({
calendarId: canViewStats ? calendarId : undefined,
- anchorDate: currentDate,
+ anchorDate: monthAnchor,
period: "month",
shifts,
});
// Anchored on the week, not the day, so tapping around inside a week reuses one cache entry
const sheetSummary = usePeriodSummary({
calendarId: statsOpen && canViewStats ? calendarId : undefined,
- anchorDate: period === "week" ? startOfWeek(selectedDay, { weekStartsOn: 1 }) : currentDate,
+ anchorDate: period === "week" ? startOfWeek(selectedDay, { weekStartsOn: 1 }) : monthAnchor,
period,
shifts,
});
const stampingEnabled = canStampPreset && isOnline && showStampBar;
+ const step = viewMode === "week" ? "week" : "month";
+ // Month and week grids only: the list already scrolls horizontally for its preset filter chips
+ const swipe = useSwipeNavigation(
+ () => onDateChange(stepDate(currentDate, step, 1)),
+ () => onDateChange(stepDate(currentDate, step, -1))
+ );
+ const swipeHandlers = !desktop && viewMode !== "list" ? swipe : undefined;
const stampPresetIds = useMemo(
() => orderStampPresets(presets).map((p) => p.id),
[presets]
@@ -183,24 +237,70 @@ export function CalendarWorkspace({
);
const hasBanner = !isOnline || isGuest || (!canCreateShift && !!calendarId);
- const grid = (
- <MonthGrid
- variant={desktop ? "desktop" : "phone"}
- calendarDays={calendarDays}
- currentDate={currentDate}
- selectedDay={selectedDay}
- shifts={visibleShifts}
- notes={notes}
- externalSyncs={externalSyncs}
- togglingDates={togglingDates}
- layout={layout}
- showShiftNotes={showShiftNotes}
- highlightedWeekdays={highlightedWeekdays}
- highlightColor={highlightColor}
- onDayClick={onDayClick}
- onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
- />
- );
+ const variant = desktop ? "desktop" : "phone";
+ const surface =
+ viewMode === "list" ? (
+ // Search and filter are per calendar, so the key drops them on a switch
+ <ShiftListView
+ key={calendarId ?? "none"}
+ variant={variant}
+ days={calendarDays}
+ selectedDay={selectedDay}
+ shifts={visibleShifts}
+ notes={notes}
+ presets={presets}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ sort={listSort}
+ combinedSort={layout.combinedSort ?? false}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ stampArmed={selectedPresetIds.length > 0}
+ canEditShift={model.canEditShift}
+ canDeleteShift={model.canDeleteShift}
+ onEditShift={actions.onEditShift}
+ onDeleteShift={actions.onDeleteShift}
+ onDayClick={onDayClick}
+ onSelectDay={onSelectDay}
+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
+ scrollTarget={scrollTarget}
+ />
+ ) : viewMode === "week" ? (
+ <WeekGrid
+ variant={variant}
+ days={calendarDays}
+ selectedDay={selectedDay}
+ shifts={visibleShifts}
+ notes={notes}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ layout={layout}
+ showShiftNotes={showShiftNotes}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ onDayClick={onDayClick}
+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
+ swipeHandlers={swipeHandlers}
+ />
+ ) : (
+ <MonthGrid
+ variant={variant}
+ calendarDays={calendarDays}
+ currentDate={currentDate}
+ selectedDay={selectedDay}
+ shifts={visibleShifts}
+ notes={notes}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ layout={layout}
+ showShiftNotes={showShiftNotes}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ onDayClick={onDayClick}
+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
+ swipeHandlers={swipeHandlers}
+ />
+ );
if (desktop) {
return (
@@ -209,7 +309,7 @@ export function CalendarWorkspace({
<div className="flex min-h-0 flex-1">
<main className="relative flex min-w-0 flex-1 flex-col pb-[18px]">
{hasBanner && <div className="flex flex-col gap-2 px-[18px] pt-3.5">{banners}</div>}
- <div className={isOnline ? "contents" : "contents [&>div]:opacity-60"}>{grid}</div>
+ <div className={isOnline ? "contents" : "contents [&>div]:opacity-60"}>{surface}</div>
{stampingEnabled && (
<StampDock
presets={presets}
@@ -225,19 +325,19 @@ export function CalendarWorkspace({
);
}
- const dateLocale = getDateLocale(locale);
-
return (
<div className="flex h-dvh flex-col bg-background">
{header}
- <main className="flex min-h-0 flex-1 flex-col overflow-y-auto">
+ {/* In list mode the list brings its own scroller, so <main> must not scroll too */}
+ <main className={cn("flex min-h-0 flex-1 flex-col", viewMode !== "list" && "overflow-y-auto")}>
{hasBanner && <div className="flex flex-col gap-2 px-3 pt-3">{banners}</div>}
- <div className="flex items-center justify-between gap-2 px-3.5 pb-[9px] pt-3">
- <h1 className="text-[19px] font-semibold tracking-[-0.015em] text-fg-strong">
- {format(currentDate, "LLLL yyyy", { locale: dateLocale })}
+ <div className="flex items-center gap-2 px-3.5 pb-[9px] pt-3">
+ <h1 className="min-w-0 flex-1 truncate text-[19px] font-semibold tracking-[-0.015em] text-fg-strong">
+ {formatPeriodCaption(currentDate, step, locale, { compact: true })}
</h1>
+ <ViewModeSwitcher value={viewMode} onChange={onViewModeChange} variant="icon" />
{isOnline ? (
- <MonthArrows currentDate={currentDate} onDateChange={onDateChange} />
+ <MonthArrows currentDate={currentDate} onDateChange={onDateChange} step={step} />
) : (
<Button
variant="outline"
@@ -250,7 +350,15 @@ export function CalendarWorkspace({
</Button>
)}
</div>
- <div className={`flex flex-1 flex-col pb-1${isOnline ? "" : " opacity-60"}`}>{grid}</div>
+ <div
+ className={cn(
+ "flex flex-1 flex-col pb-1",
+ viewMode === "list" && "min-h-0",
+ !isOnline && "opacity-60"
+ )}
+ >
+ {surface}
+ </div>
</main>
<div className="shrink-0">
{stampingEnabled && (
@@ -270,8 +378,24 @@ export function CalendarWorkspace({
setPeriod("month");
setStatsOpen(true);
}}
- onOpenMonthShifts={actions.onOpenMonthShifts}
+ onShowList={actions.onShowList}
onAddShift={model.canAddShift ? actions.onAddShift : undefined}
+ list={
+ viewMode === "list"
+ ? {
+ nextShift,
+ onJump: () => {
+ if (!nextShift?.date) return;
+ const day = nextShift.date as Date;
+ onSelectDay(day);
+ setScrollTarget((prev) => ({
+ key: formatDateToLocal(day),
+ nonce: (prev?.nonce ?? 0) + 1,
+ }));
+ },
+ }
+ : undefined
+ }
/>
</div>
<MobileDaySheet
diff --git a/components/day-cell-entries.tsx b/components/day-cell-entries.tsx
new file mode 100644
index 0000000..9b0cfa3
--- /dev/null
+++ b/components/day-cell-entries.tsx
@@ -0,0 +1,375 @@
+"use client";
+
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslations } from "next-intl";
+import { CalendarClock, RefreshCw, StickyNote, UserPlus } from "lucide-react";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
+import { formatDateToLocal } from "@/lib/date-utils";
+import { findNotesForDate } from "@/lib/event-utils";
+import {
+ DayLayoutOptions,
+ DayShiftLayout,
+ buildDayShiftLayout,
+ formatSignupCapacityLabel,
+ formatTimeRange,
+ shiftVars,
+} from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+import { useCalendars } from "@/hooks/useCalendars";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useAuth } from "@/hooks/useAuth";
+import { useQuickSelfSignup, useShiftSignupPermission } from "@/hooks/useShiftSignups";
+
+const LONG_PRESS_MS = 500;
+
+// The filled day number of "today", shared by every grid and the list
+export const TODAY_BADGE = "bg-brand font-semibold text-white dark:bg-brand-dot dark:text-[#0a1020]";
+
+export interface DayContent {
+ layout: DayShiftLayout;
+ events: CalendarNote[];
+ notes: CalendarNote[];
+}
+
+/** One pass over the shifts instead of scanning every shift and note per day. */
+export function buildDayContents(
+ days: Date[],
+ shifts: ShiftWithCalendar[],
+ notes: CalendarNote[],
+ externalSyncs: ExternalSync[],
+ layout: DayLayoutOptions,
+ includeDay: (day: Date) => boolean
+): Map<string, DayContent> {
+ const shiftsByDay = new Map<string, ShiftWithCalendar[]>();
+ for (const shift of shifts) {
+ if (!shift.date) continue;
+ const key = formatDateToLocal(shift.date as Date);
+ const list = shiftsByDay.get(key);
+ if (list) list.push(shift);
+ else shiftsByDay.set(key, [shift]);
+ }
+
+ const contents = new Map<string, DayContent>();
+ for (const day of days) {
+ const key = formatDateToLocal(day);
+ const included = includeDay(day);
+ const dayNotes = included ? findNotesForDate(notes, day) : [];
+ contents.set(key, {
+ layout: buildDayShiftLayout(included ? (shiftsByDay.get(key) ?? []) : [], externalSyncs, layout),
+ events: dayNotes.filter((n) => n.type === "event"),
+ notes: dayNotes.filter((n) => n.type !== "event"),
+ });
+ }
+ return contents;
+}
+
+/** Whether signups are on for a calendar; unknown calendars count as enabled. */
+export function useSignupsEnabled(): (calendarId: string) => boolean {
+ const { calendars } = useCalendars();
+ const { isAuthEnabled } = useAuthFeatures();
+ const byId = useMemo(
+ () => new Map(calendars.map((c) => [c.id, isAuthEnabled && (c.signupsEnabled ?? true)])),
+ [calendars, isAuthEnabled]
+ );
+ return (calendarId) => byId.get(calendarId) ?? true;
+}
+
+export interface DayPressHandlers {
+ onClick: () => void;
+ onContextMenu: (e: React.MouseEvent) => void;
+ onTouchStart: () => void;
+ onTouchEnd: () => void;
+ onTouchMove: () => void;
+}
+
+/** Click, right-click and 500ms long-press for a day; the long press swallows the click that follows it. */
+export function useDayPress(
+ onDayClick: (day: Date) => void,
+ onDayContextMenu?: (day: Date) => void
+): (day: Date) => DayPressHandlers {
+ const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const longPressed = useRef(false);
+
+ useEffect(
+ () => () => {
+ if (pressTimer.current) clearTimeout(pressTimer.current);
+ },
+ []
+ );
+
+ const cancelPress = () => {
+ if (pressTimer.current) clearTimeout(pressTimer.current);
+ pressTimer.current = null;
+ };
+
+ return (day) => ({
+ onClick: () => {
+ if (longPressed.current) {
+ longPressed.current = false;
+ return;
+ }
+ onDayClick(day);
+ },
+ onContextMenu: (e) => {
+ e.preventDefault();
+ onDayContextMenu?.(day);
+ },
+ onTouchStart: () => {
+ longPressed.current = false;
+ if (!onDayContextMenu) return;
+ pressTimer.current = setTimeout(() => {
+ longPressed.current = true;
+ onDayContextMenu(day);
+ }, LONG_PRESS_MS);
+ },
+ onTouchEnd: cancelPress,
+ onTouchMove: cancelPress,
+ });
+}
+
+/** Compact "N" / "N/capacity" badge. */
+export function SignupBadge({ shift, enabled }: { shift: ShiftWithCalendar; enabled: boolean }) {
+ const t = useTranslations();
+ if (!enabled) return null;
+ const count = shift.signups?.length ?? 0;
+ const capacity = shift.signupCapacity ?? null;
+ if (count === 0 && capacity == null) return null;
+ const label = capacity != null ? formatSignupCapacityLabel(t, count, capacity) : null;
+ return (
+ <span
+ className={cn(
+ "shrink-0 rounded-[4px] px-1 font-mono text-[10px] leading-4",
+ label?.isFull ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken/70 text-fg-tertiary"
+ )}
+ title={label?.text}
+ >
+ {capacity != null ? `${count}/${capacity}` : count}
+ </span>
+ );
+}
+
+/** Quick self-assign; renders nothing when the viewer can't or already did. Shared with ShiftDetailRow. */
+export function QuickSignupButton({
+ shift,
+ size = "md",
+}: {
+ shift: ShiftWithCalendar;
+ /** "sm" fits a shift chip, "md" a full-height row like ShiftDetailRow */
+ size?: "sm" | "md";
+}) {
+ const t = useTranslations();
+ const { user: currentUser } = useAuth();
+ const { canManageOwn } = useShiftSignupPermission(shift.calendarId);
+ const { signUpForShift, isPending: signingUp } = useQuickSelfSignup();
+ const signups = shift.signups ?? [];
+ const capacity = shift.signupCapacity ?? null;
+ const alreadySignedUp = !!currentUser && signups.some((s) => s.id === currentUser.id);
+ const isFull = capacity != null && signups.length >= capacity;
+ if (!canManageOwn || alreadySignedUp || isFull) return null;
+
+ return (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ signUpForShift(shift.id);
+ }}
+ disabled={signingUp}
+ aria-label={t("shiftSignup.addSelf")}
+ title={t("shiftSignup.addSelf")}
+ className={cn(
+ "flex shrink-0 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken disabled:opacity-40",
+ size === "sm" ? "size-5" : "size-7"
+ )}
+ >
+ <UserPlus className={size === "sm" ? "size-3.5" : "size-4"} />
+ </button>
+ );
+}
+
+const CHIP =
+ "shift-chip flex min-w-0 shrink-0 gap-1.5 rounded-[6px] py-0.5 pr-[7px] dark:[--shift-tint:14%]";
+// Month cells cut titles to one line; week and list let them wrap
+const lineClass = (wrap: boolean) => (wrap ? "block break-words" : "block truncate");
+
+function ChipTime({
+ shift,
+ full,
+ stacked = false,
+}: {
+ shift: ShiftWithCalendar;
+ full: boolean;
+ /** Below the title instead of beside it, for wrap mode where the range no longer fits on one line */
+ stacked?: boolean;
+}) {
+ const t = useTranslations();
+ return (
+ <span
+ className={
+ stacked
+ ? "mt-0.5 block whitespace-normal break-words font-mono text-[10.5px] leading-4 opacity-75"
+ : "shrink-0 whitespace-nowrap font-mono text-[10.5px] leading-4 opacity-75"
+ }
+ >
+ {shift.isAllDay
+ ? t("calendarView.allDayShort")
+ : full || shift.segments?.length
+ ? formatTimeRange(shift)
+ : shift.startTime.slice(0, 5)}
+ </span>
+ );
+}
+
+export function ShiftChip({
+ shift,
+ showNote,
+ signupsEnabled,
+ wrap = false,
+ interactive = false,
+}: {
+ shift: ShiftWithCalendar;
+ showNote: boolean;
+ signupsEnabled: boolean;
+ wrap?: boolean;
+ /** Week view only: the cell is a div, not a button, so a nested signup button is valid here */
+ interactive?: boolean;
+}) {
+ const title = `${shift.title}${shift.notes ? `\n${shift.notes}` : ""}`;
+
+ // Wrap mode: the time no longer fits beside the title without breaking it per syllable,
+ // so it moves below the title/note; only the signup badge stays on the title's row.
+ if (wrap) {
+ return (
+ <span className={cn(CHIP, "pl-[5px]")} style={shiftVars(shift.color)} title={title}>
+ <span className="shift-rail w-[3px] shrink-0 self-stretch rounded-full" />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-start gap-1.5">
+ <span className={cn(lineClass(wrap), "min-w-0 flex-1 text-[11.5px] font-medium leading-4")}>
+ {shift.title}
+ </span>
+ <SignupBadge shift={shift} enabled={signupsEnabled} />
+ {interactive && <QuickSignupButton shift={shift} />}
+ </span>
+ {showNote && shift.notes && (
+ <span className={cn(lineClass(wrap), "text-[10.5px] leading-[14px] opacity-75")}>
+ {shift.notes}
+ </span>
+ )}
+ <ChipTime shift={shift} full={wrap} stacked />
+ </span>
+ </span>
+ );
+ }
+
+ return (
+ <span className={cn(CHIP, "pl-[5px]")} style={shiftVars(shift.color)} title={title}>
+ <span className="shift-rail w-[3px] shrink-0 self-stretch rounded-full" />
+ <span className="min-w-0 flex-1">
+ <span className={cn(lineClass(wrap), "text-[11.5px] font-medium leading-4")}>
+ {shift.title}
+ </span>
+ {showNote && shift.notes && (
+ <span className={cn(lineClass(wrap), "text-[10.5px] leading-[14px] opacity-75")}>
+ {shift.notes}
+ </span>
+ )}
+ </span>
+ <SignupBadge shift={shift} enabled={signupsEnabled} />
+ {interactive && <QuickSignupButton shift={shift} />}
+ <ChipTime shift={shift} full={wrap} />
+ </span>
+ );
+}
+
+/** The sync icon takes the rail's place so imported entries stay recognisable. */
+export function ExternalShiftChip({
+ shift,
+ wrap = false,
+}: {
+ shift: ShiftWithCalendar;
+ wrap?: boolean;
+}) {
+ // Wrap mode: title column stacks the time below itself instead of beside it
+ if (wrap) {
+ return (
+ <span className={cn(CHIP, "pl-[5px] items-start")} style={shiftVars(shift.color)} title={shift.title}>
+ <RefreshCw className="mt-0.5 size-3 shrink-0" />
+ <span className="min-w-0 flex-1">
+ <span className={cn(lineClass(wrap), "text-[11.5px] font-medium leading-4")}>
+ {shift.title}
+ </span>
+ <ChipTime shift={shift} full={wrap} stacked />
+ </span>
+ </span>
+ );
+ }
+
+ return (
+ <span className={cn(CHIP, "pl-[5px] items-center")} style={shiftVars(shift.color)} title={shift.title}>
+ <RefreshCw className="size-3 shrink-0" />
+ <span className={cn("min-w-0 flex-1 text-[11.5px] font-medium leading-4", lineClass(wrap))}>
+ {shift.title}
+ </span>
+ <ChipTime shift={shift} full={wrap} />
+ </span>
+ );
+}
+
+export function EventChip({ note, wrap = false }: { note: CalendarNote; wrap?: boolean }) {
+ return (
+ <span
+ className={cn(
+ "flex min-w-0 shrink-0 gap-1.5 rounded-[6px] bg-cell-event px-[7px] shadow-[inset_0_0_0_1px_var(--cell-event-line)]",
+ wrap ? "items-start py-0.5" : "h-5 items-center"
+ )}
+ title={note.note}
+ >
+ <CalendarClock
+ className={cn("shift-icon size-3 shrink-0", wrap && "mt-0.5")}
+ style={shiftVars(note.color || undefined)}
+ />
+ <span
+ className={cn(
+ "min-w-0 flex-1 text-[11.5px] font-medium text-cell-event-ink",
+ wrap ? "break-words leading-4" : "truncate"
+ )}
+ >
+ {note.note}
+ </span>
+ </span>
+ );
+}
+
+export function NoteLine({ note, wrap = false }: { note: CalendarNote; wrap?: boolean }) {
+ return (
+ <span
+ className={cn("flex min-w-0 shrink-0 gap-1.5 px-1", wrap ? "items-start py-px" : "h-[18px] items-center")}
+ title={note.note}
+ >
+ <StickyNote className={cn("size-3 shrink-0 text-cell-note", wrap && "mt-0.5")} />
+ <span
+ className={cn(
+ "min-w-0 flex-1 text-[11.5px] text-fg-body dark:text-fg-secondary",
+ wrap ? "break-words leading-4" : "truncate"
+ )}
+ >
+ {note.note}
+ </span>
+ </span>
+ );
+}
+
+/** Count-only pill for an external sync in "minimal" display mode. */
+export function MinimalSyncCounter({ sync, count }: { sync: ExternalSync; count: number }) {
+ return (
+ <span
+ className="shift-chip flex shrink-0 items-center gap-1 rounded-[6px] px-[5px] py-0.5 dark:[--shift-tint:14%]"
+ style={shiftVars(sync.color)}
+ title={sync.name}
+ >
+ <RefreshCw className="size-3 shrink-0" />
+ <span className="font-mono text-[11px] font-semibold leading-4">{count}</span>
+ </span>
+ );
+}
diff --git a/components/day-detail.tsx b/components/day-detail.tsx
index 173c5ac..69f0811 100644
--- a/components/day-detail.tsx
+++ b/components/day-detail.tsx
@@ -9,7 +9,6 @@ import {
RefreshCw,
StickyNote,
Trash2,
- UserPlus,
} from "lucide-react";
import {
DropdownMenu,
@@ -30,8 +29,8 @@ import {
import { PeriodSummary } from "@/hooks/useDaySummary";
import { cn, getUserInitials } from "@/lib/utils";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import { useAuth } from "@/hooks/useAuth";
-import { useQuickSelfSignup, useShiftSignupPermission } from "@/hooks/useShiftSignups";
+import { useShiftSignupPermission } from "@/hooks/useShiftSignups";
+import { QuickSignupButton } from "@/components/day-cell-entries";
/** Compact avatar stack for who signed up; renders nothing when unused. */
function ShiftSignupBadge({
@@ -109,7 +108,11 @@ interface ShiftDetailRowProps {
canEdit: boolean;
canDelete: boolean;
actions: "menu" | "inline";
+ /** List view: title and note wrap instead of truncating */
+ fullTitle?: boolean;
onEdit: (shift: ShiftWithCalendar) => void;
+ /** What a click on the row itself does; defaults to `onEdit`, which the menu always keeps */
+ onOpen?: (shift: ShiftWithCalendar) => void;
onDelete: (shift: ShiftWithCalendar) => void;
}
@@ -118,7 +121,9 @@ export function ShiftDetailRow({
canEdit,
canDelete,
actions,
+ fullTitle = false,
onEdit,
+ onOpen,
onDelete,
}: ShiftDetailRowProps) {
const t = useTranslations();
@@ -130,18 +135,11 @@ export function ShiftDetailRow({
const deletable = canDelete && !synced;
const minutes = getShiftMinutes(shift);
- const { user: currentUser } = useAuth();
- const { canManageOwn, signupsEnabled } = useShiftSignupPermission(shift.calendarId);
- const { signUpForShift, isPending: signingUp } = useQuickSelfSignup();
- const signups = shift.signups ?? [];
- const capacity = shift.signupCapacity ?? null;
- const alreadySignedUp = !!currentUser && signups.some((s) => s.id === currentUser.id);
- const isFull = capacity != null && signups.length >= capacity;
- const showQuickSignup = canManageOwn && !alreadySignedUp && !isFull;
+ const { signupsEnabled } = useShiftSignupPermission(shift.calendarId);
return (
<div
- onClick={() => onEdit(shift)}
+ onClick={() => (onOpen ?? onEdit)(shift)}
className="flex cursor-pointer items-center gap-[11px] rounded-lg border border-line bg-surface-card px-3 py-[11px] transition-colors hover:bg-surface-panel"
>
<span
@@ -149,32 +147,20 @@ export function ShiftDetailRow({
style={shiftVars(shift.color)}
/>
<div className="min-w-0 flex-1">
- <div className="truncate text-[13.5px] font-semibold text-fg-strong">
+ <div className={cn("text-[13.5px] font-semibold text-fg-strong", fullTitle ? "break-words" : "truncate")}>
{shift.title}
</div>
<div className="mt-0.5 font-mono text-xs text-fg-tertiary">
{shift.isAllDay ? t("shift.allDayShift") : formatTimeRange(shift)}
</div>
{shift.notes && (
- <div className="mt-1 line-clamp-2 text-xs text-fg-secondary">{shift.notes}</div>
+ <div className={cn("mt-1 text-xs text-fg-secondary", fullTitle ? "whitespace-pre-line break-words" : "line-clamp-2")}>
+ {shift.notes}
+ </div>
)}
</div>
<ShiftSignupBadge shift={shift} signupsEnabled={signupsEnabled} />
- {showQuickSignup && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- signUpForShift(shift.id);
- }}
- disabled={signingUp}
- aria-label={t("shiftSignup.addSelf")}
- title={t("shiftSignup.addSelf")}
- className="flex size-7 shrink-0 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken disabled:opacity-40"
- >
- <UserPlus className="size-4" />
- </button>
- )}
+ <QuickSignupButton shift={shift} />
{synced && (
<span
className="flex items-center gap-1 rounded-full bg-surface-sunken px-2 py-0.5 text-[11px] font-semibold text-fg-secondary"
@@ -199,7 +185,12 @@ export function ShiftDetailRow({
>
<Ellipsis className="size-4" />
</DropdownMenuTrigger>
- <DropdownMenuContent align="end">
+ <DropdownMenuContent
+ align="end"
+ // Portal content bubbles into the row below; keep menu clicks/holds from stamping it
+ onClick={(e) => e.stopPropagation()}
+ onTouchStart={(e) => e.stopPropagation()}
+ >
{editable && (
<DropdownMenuItem
onClick={(e) => {
diff --git a/components/day-inspector.tsx b/components/day-inspector.tsx
index 4912a6a..3885733 100644
--- a/components/day-inspector.tsx
+++ b/components/day-inspector.tsx
@@ -25,7 +25,8 @@ export interface DayActions {
onAddNote: () => void;
onOpenNote: (note: CalendarNote) => void;
onOpenStats: () => void;
- onOpenMonthShifts: () => void;
+ /** Switches to the list view; absent while it is already showing */
+ onShowList?: () => void;
}
export interface DayViewModel {
@@ -157,38 +158,42 @@ export function DayInspector({
)}
</div>
- <div className="border-t border-line px-[18px] py-3.5">
- <div className={cn("flex items-center justify-between", canViewStats && "mb-2.5")}>
- <span className="eyebrow">
- {canViewStats
- ? t("calendarView.monthTotal", { month: monthName })
- : t("calendarView.allShiftsIn", { month: monthName })}
- </span>
- <div className="flex items-center gap-0.5">
- <button
- type="button"
- onClick={actions.onOpenMonthShifts}
- title={t("calendarView.allShiftsIn", { month: monthName })}
- aria-label={t("calendarView.allShiftsIn", { month: monthName })}
- className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
- >
- <List className="size-[15px]" />
- </button>
- {canViewStats && (
- <button
- type="button"
- onClick={actions.onOpenStats}
- title={t("calendarView.openStats")}
- aria-label={t("calendarView.openStats")}
- className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
- >
- <ArrowUpRight className="size-[15px]" />
- </button>
- )}
+ {(canViewStats || actions.onShowList) && (
+ <div className="border-t border-line px-[18px] py-3.5">
+ <div className={cn("flex items-center justify-between", canViewStats && "mb-2.5")}>
+ <span className="eyebrow">
+ {canViewStats
+ ? t("calendarView.monthTotal", { month: monthName })
+ : t("calendarView.allShiftsIn", { month: monthName })}
+ </span>
+ <div className="flex items-center gap-0.5">
+ {actions.onShowList && (
+ <button
+ type="button"
+ onClick={actions.onShowList}
+ title={t("calendarView.allShiftsIn", { month: monthName })}
+ aria-label={t("calendarView.allShiftsIn", { month: monthName })}
+ className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
+ >
+ <List className="size-[15px]" />
+ </button>
+ )}
+ {canViewStats && (
+ <button
+ type="button"
+ onClick={actions.onOpenStats}
+ title={t("calendarView.openStats")}
+ aria-label={t("calendarView.openStats")}
+ className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
+ >
+ <ArrowUpRight className="size-[15px]" />
+ </button>
+ )}
+ </div>
</div>
+ {canViewStats && <PeriodSummaryView summary={summary} />}
</div>
- {canViewStats && <PeriodSummaryView summary={summary} />}
- </div>
+ )}
</aside>
);
}
diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsx
index 837f3eb..0a42875 100644
--- a/components/dialog-manager.tsx
+++ b/components/dialog-manager.tsx
@@ -8,7 +8,7 @@ import { ViewSettingsSheet, ViewSettingsState } from "@/components/view-settings
import { NoteSheet } from "@/components/note-sheet";
import { NotesListDialog } from "@/components/notes-list-dialog";
import { PresetManageSheet } from "@/components/preset-manage-sheet";
-import { MonthShiftsDialog, MonthStatsDialog } from "@/components/month-dialogs";
+import { MonthStatsDialog } from "@/components/month-dialogs";
import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote } from "@/lib/db/schema";
@@ -74,18 +74,14 @@ interface DialogManagerProps {
onDeleteNoteFromList: (noteId: string) => void;
onAddNewNote: () => void;
- // Month summary dialogs opened from the day inspector
+ // Month summary dialog opened from the day inspector
currentDate: Date;
- shifts: ShiftWithCalendar[];
/** Per-shift own/any precision (editOwnShift/editAnyShift) — a calendar-wide boolean can't tell own from another's entry. */
canEditShift: (shift: ShiftWithCalendar) => boolean;
/** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) — independent from canEditShift. */
canDeleteShift: (shift: ShiftWithCalendar) => boolean;
showMonthStatsDialog: boolean;
onMonthStatsDialogChange: (open: boolean) => void;
- showMonthShiftsDialog: boolean;
- onMonthShiftsDialogChange: (open: boolean) => void;
- onDeleteShift: (shift: ShiftWithCalendar) => void;
// Preset management opened from the stamp dock
showPresetManageDialog: boolean;
@@ -178,16 +174,6 @@ export function DialogManager(props: DialogManagerProps) {
currentDate={props.currentDate}
calendarId={props.selectedCalendar || undefined}
/>
- <MonthShiftsDialog
- open={props.showMonthShiftsDialog}
- onOpenChange={props.onMonthShiftsDialogChange}
- currentDate={props.currentDate}
- shifts={props.shifts}
- canEditShift={props.canEditShift}
- canDeleteShift={props.canDeleteShift}
- onEditShift={(shift) => props.onEditShiftFromDayDialog?.(shift)}
- onDeleteShift={props.onDeleteShift}
- />
{props.selectedCalendar && (
<PresetManageSheet
open={props.showPresetManageDialog}
diff --git a/components/mobile-day-sheet.tsx b/components/mobile-day-sheet.tsx
index 3e04eb6..e8958c4 100644
--- a/components/mobile-day-sheet.tsx
+++ b/components/mobile-day-sheet.tsx
@@ -2,8 +2,16 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
-import { format, getISOWeek } from "date-fns";
-import { ChevronDown, ChevronRight, ChevronUp, List, Plus, StickyNote } from "lucide-react";
+import { format, getISOWeek, isToday, isTomorrow } from "date-fns";
+import {
+ ChartColumn,
+ ChevronDown,
+ ChevronRight,
+ ChevronUp,
+ List,
+ Plus,
+ StickyNote,
+} from "lucide-react";
import {
Drawer,
DrawerContent,
@@ -19,6 +27,9 @@ import {
} from "@/components/day-detail";
import { DayActions, DayViewModel, useDayLabels } from "@/components/day-inspector";
import { PeriodSummary, StatsPeriod } from "@/hooks/useDaySummary";
+import { ShiftWithCalendar } from "@/lib/types";
+import { formatLongDate } from "@/lib/date-utils";
+import { formatTimeRange, shiftVars } from "@/lib/shift-display";
import { getDateLocale } from "@/lib/locales";
const TALL = 0.92;
@@ -31,18 +42,22 @@ export function MobileDayFooter({
summary,
currentDate,
onOpenStats,
- onOpenMonthShifts,
+ onShowList,
onAddShift,
canViewStats,
+ list,
}: {
summary: PeriodSummary;
/** Only needed for the "all shifts in <month>" fallback label when stats are hidden */
currentDate: Date;
onOpenStats: () => void;
- onOpenMonthShifts: () => void;
+ /** Switches to the list view; absent while it is already showing */
+ onShowList?: () => void;
/** Hidden when the calendar can't be edited */
onAddShift?: () => void;
canViewStats: boolean;
+ /** List view replaces the month figures with the next shift and a jump to it */
+ list?: { nextShift: ShiftWithCalendar | null; onJump: () => void };
}) {
const t = useTranslations();
const locale = useLocale();
@@ -62,9 +77,51 @@ export function MobileDayFooter({
]
: [];
+ const next = list?.nextShift ?? null;
+ const nextDay = next?.date
+ ? isToday(next.date)
+ ? t("calendarView.today")
+ : isTomorrow(next.date)
+ ? t("calendarView.tomorrow")
+ : formatLongDate(next.date, locale, { month: "short" })
+ : null;
+
return (
<div className="flex items-center gap-2.5 border-t border-line bg-surface-panel px-3.5 pb-[max(9px,env(safe-area-inset-bottom))] pt-[9px]">
- {canViewStats ? (
+ {list ? (
+ <>
+ <button
+ type="button"
+ onClick={list.onJump}
+ disabled={!next}
+ className="flex min-w-0 flex-1 items-center gap-2.5 py-0.5 text-left"
+ >
+ {next && (
+ <span className="shift-rail h-[30px] w-1 shrink-0 rounded-full" style={shiftVars(next.color)} />
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[10.5px] leading-[14px] text-fg-tertiary">
+ {t("calendarView.nextShift")}
+ </span>
+ <span className="block truncate text-[13px] font-semibold leading-5 text-fg-strong">
+ {next
+ ? `${next.title} · ${nextDay}${next.isAllDay ? "" : ` · ${formatTimeRange(next)}`}`
+ : t("calendarView.noUpcomingShift")}
+ </span>
+ </span>
+ </button>
+ {canViewStats && (
+ <button
+ type="button"
+ onClick={onOpenStats}
+ aria-label={t("calendarView.openStats")}
+ className="flex size-10 shrink-0 items-center justify-center rounded-[11px] border border-line text-fg-secondary"
+ >
+ <ChartColumn className="size-[18px]" />
+ </button>
+ )}
+ </>
+ ) : canViewStats ? (
<button
type="button"
onClick={onOpenStats}
@@ -84,10 +141,10 @@ export function MobileDayFooter({
</span>
<ChevronUp className="size-4 shrink-0 text-fg-tertiary" />
</button>
- ) : (
+ ) : onShowList ? (
<button
type="button"
- onClick={onOpenMonthShifts}
+ onClick={onShowList}
className="flex min-w-0 flex-1 items-center gap-2.5 py-0.5 text-left"
>
<List className="size-4 shrink-0 text-fg-tertiary" />
@@ -98,6 +155,8 @@ export function MobileDayFooter({
</span>
<ChevronRight className="size-4 shrink-0 text-fg-tertiary" />
</button>
+ ) : (
+ <span className="flex-1" />
)}
{onAddShift && (
<button
@@ -387,10 +446,10 @@ export function MobileStatsSheet({
]}
/>
<PeriodSummaryView summary={summary} columns="cards" />
- {period === "month" && (
+ {period === "month" && actions.onShowList && (
<button
type="button"
- onClick={run(actions.onOpenMonthShifts)}
+ onClick={run(actions.onShowList)}
className="flex items-center gap-2.5 rounded-lg border border-line bg-surface-card px-3 py-3 text-left"
>
<List className="size-4 text-fg-secondary" />
diff --git a/components/month-dialogs.tsx b/components/month-dialogs.tsx
index b614e8b..a9878df 100644
--- a/components/month-dialogs.tsx
+++ b/components/month-dialogs.tsx
@@ -1,15 +1,8 @@
"use client";
-import { useMemo } from "react";
-import { useLocale, useTranslations } from "next-intl";
-import { format } from "date-fns";
+import { useTranslations } from "next-intl";
import { PanelDialog } from "@/components/panel-dialog";
import { ShiftStats } from "@/components/shift-stats";
-import { ShiftDetailRow } from "@/components/day-detail";
-import { ShiftWithCalendar } from "@/lib/types";
-import { getDateLocale } from "@/lib/locales";
-import { formatDateToLocal, formatLongDate } from "@/lib/date-utils";
-import { formatHours, getShiftMinutes, sortShifts } from "@/lib/shift-display";
interface MonthDialogProps {
open: boolean;
@@ -36,104 +29,3 @@ export function MonthStatsDialog({
</PanelDialog>
);
}
-
-export function MonthShiftsDialog({
- open,
- onOpenChange,
- currentDate,
- shifts,
- canEditShift,
- canDeleteShift,
- onEditShift,
- onDeleteShift,
-}: MonthDialogProps & {
- shifts: ShiftWithCalendar[];
- /** Per-shift own/any precision (editOwnShift/editAnyShift) */
- canEditShift: (shift: ShiftWithCalendar) => boolean;
- /** Per-shift own/any precision (deleteOwnShift/deleteAnyShift) — independent from canEditShift */
- canDeleteShift: (shift: ShiftWithCalendar) => boolean;
- onEditShift: (shift: ShiftWithCalendar) => void;
- onDeleteShift: (shift: ShiftWithCalendar) => void;
-}) {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
-
- const days = useMemo(() => {
- const inMonth = shifts.filter((s) => {
- const d = s.date as Date | null;
- return (
- d &&
- d.getMonth() === currentDate.getMonth() &&
- d.getFullYear() === currentDate.getFullYear()
- );
- });
- const groups = new Map<string, { date: Date; shifts: ShiftWithCalendar[] }>();
- for (const shift of inMonth) {
- const date = shift.date as Date;
- const key = formatDateToLocal(date);
- const group = groups.get(key) ?? { date, shifts: [] };
- group.shifts.push(shift);
- groups.set(key, group);
- }
- return [...groups.entries()]
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([key, group]) => ({
- key,
- date: group.date,
- shifts: sortShifts(group.shifts, "startTime"),
- }));
- }, [shifts, currentDate]);
-
- const total = days.reduce((sum, d) => sum + d.shifts.length, 0);
- const monthLabel = format(currentDate, "LLLL yyyy", { locale: dateLocale });
-
- return (
- <PanelDialog
- open={open}
- onOpenChange={onOpenChange}
- title={t("calendarView.allShiftsIn", {
- month: format(currentDate, "LLLL", { locale: dateLocale }),
- })}
- description={`${monthLabel} · ${t("calendarView.shiftCount", { count: total })}`}
- width="md"
- >
- {days.length === 0 ? (
- <p className="py-6 text-center text-[13px] text-fg-tertiary">
- {t("shift.noShiftsInMonth")}
- </p>
- ) : (
- <div className="flex flex-col gap-4">
- {days.map((day) => {
- const minutes = day.shifts.reduce((sum, s) => sum + getShiftMinutes(s), 0);
- return (
- <section key={day.key} className="flex flex-col gap-1.5">
- <h3 className="flex items-baseline gap-2 text-[13px] font-semibold text-fg-strong">
- {formatLongDate(day.date, locale)}
- <span className="font-mono text-[11.5px] font-normal text-fg-tertiary">
- {t("calendarView.shiftCount", { count: day.shifts.length })}
- {minutes > 0 && ` · ${formatHours(minutes, locale)}`}
- </span>
- </h3>
- {day.shifts.map((shift) => (
- <ShiftDetailRow
- key={shift.id}
- shift={shift}
- canEdit={canEditShift(shift)}
- canDelete={canDeleteShift(shift)}
- actions="menu"
- onEdit={(s) => {
- onOpenChange(false);
- onEditShift(s);
- }}
- onDelete={onDeleteShift}
- />
- ))}
- </section>
- );
- })}
- </div>
- )}
- </PanelDialog>
- );
-}
diff --git a/components/month-grid.tsx b/components/month-grid.tsx
index 37a5ca0..e137efa 100644
--- a/components/month-grid.tsx
+++ b/components/month-grid.tsx
@@ -7,18 +7,21 @@ import { CalendarClock, RefreshCw, StickyNote } from "lucide-react";
import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote, ExternalSync } from "@/lib/db/schema";
import { formatDateToLocal } from "@/lib/date-utils";
-import { findNotesForDate } from "@/lib/event-utils";
-import {
- DayLayoutOptions,
- DayShiftLayout,
- buildDayShiftLayout,
- formatSignupCapacityLabel,
- formatTimeRange,
- shiftVars,
-} from "@/lib/shift-display";
+import { DayLayoutOptions, shiftVars } from "@/lib/shift-display";
import { cn } from "@/lib/utils";
-import { useCalendars } from "@/hooks/useCalendars";
-import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import {
+ DayContent,
+ EventChip,
+ ExternalShiftChip,
+ MinimalSyncCounter,
+ NoteLine,
+ ShiftChip,
+ SignupBadge,
+ TODAY_BADGE,
+ buildDayContents,
+ useDayPress,
+ useSignupsEnabled,
+} from "@/components/day-cell-entries";
const WEEKDAY_KEYS = [
"monday",
@@ -30,11 +33,6 @@ const WEEKDAY_KEYS = [
"sunday",
] as const;
-const LONG_PRESS_MS = 500;
-
-// The filled day number of "today", shared by the desktop, phone and compare cells
-const TODAY_BADGE = "bg-brand font-semibold text-white dark:bg-brand-dot dark:text-[#0a1020]";
-
// Cell geometry in px. These mirror the Tailwind sizes of the cell markup below;
// change both together or the fitting clips rows.
const DESKTOP_MAX_ROWS = 4;
@@ -119,12 +117,6 @@ function useGridSize(enabled: boolean) {
return [ref, size] as const;
}
-interface DayContent {
- layout: DayShiftLayout;
- events: CalendarNote[];
- notes: CalendarNote[];
-}
-
interface MonthGridProps {
calendarDays: Date[];
currentDate: Date;
@@ -142,6 +134,11 @@ interface MonthGridProps {
onDayContextMenu?: (date: Date) => void;
/** "compare" is the narrow desktop column used side by side in compare mode */
variant?: Variant;
+ /** Phone only: swipe left/right across the grid to step the month */
+ swipeHandlers?: {
+ onTouchStart: (e: React.TouchEvent) => void;
+ onTouchEnd: (e: React.TouchEvent) => void;
+ };
}
export function MonthGrid({
@@ -159,15 +156,12 @@ export function MonthGrid({
onDayClick,
onDayContextMenu,
variant = "desktop",
+ swipeHandlers,
}: MonthGridProps) {
const t = useTranslations();
const locale = useLocale();
- const { calendars } = useCalendars();
- const { isAuthEnabled } = useAuthFeatures();
- const signupsEnabledById = useMemo(
- () => new Map(calendars.map((c) => [c.id, isAuthEnabled && (c.signupsEnabled ?? true)])),
- [calendars, isAuthEnabled]
- );
+ const signupsEnabled = useSignupsEnabled();
+ const dayPress = useDayPress(onDayClick, onDayContextMenu);
const phone = variant === "phone";
const desktop = variant === "desktop";
// 2024-01-01 was a Monday
@@ -175,8 +169,6 @@ export function MonthGrid({
const formatter = new Intl.DateTimeFormat(locale, { weekday: "long" });
return WEEKDAY_KEYS.map((_, i) => formatter.format(new Date(2024, 0, 1 + i)));
}, [locale]);
- const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const longPressed = useRef(false);
const [gridRef, gridSize] = useGridSize(variant !== "compare");
const rows = Math.max(1, Math.ceil(calendarDays.length / 7));
const measured = gridSize.height > 0;
@@ -184,62 +176,20 @@ export function MonthGrid({
? Math.max(PHONE_MIN_ROW, (gridSize.height - (rows - 1) * PHONE_GAP) / rows)
: (gridSize.height - (rows - 1)) / rows;
const colWidth = gridSize.width > 0 ? (gridSize.width - 8) / 7 : PHONE_FALLBACK_COL;
- // Compact "N" / "N/capacity" badge shared by the desktop chip and the compare row
- const signupBadge = (shift: ShiftWithCalendar) => {
- if (!(signupsEnabledById.get(shift.calendarId) ?? true)) return null;
- const count = shift.signups?.length ?? 0;
- const capacity = shift.signupCapacity ?? null;
- if (count === 0 && capacity == null) return null;
- const label = capacity != null ? formatSignupCapacityLabel(t, count, capacity) : null;
- return (
- <span
- className={cn(
- "shrink-0 rounded-[4px] px-1 font-mono text-[10px] leading-4",
- label?.isFull ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken/70 text-fg-tertiary"
- )}
- title={label?.text}
- >
- {capacity != null ? `${count}/${capacity}` : count}
- </span>
- );
- };
-
- useEffect(
- () => () => {
- if (pressTimer.current) clearTimeout(pressTimer.current);
- },
- []
- );
// One pass over the month instead of scanning every shift and note per cell
const { maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort } = layout;
const dayContents = useMemo(() => {
const month = currentDate.getMonth();
- const shiftsByDay = new Map<string, ShiftWithCalendar[]>();
- for (const shift of shifts) {
- if (!shift.date) continue;
- const key = formatDateToLocal(shift.date as Date);
- const list = shiftsByDay.get(key);
- if (list) list.push(shift);
- else shiftsByDay.set(key, [shift]);
- }
-
- const contents = new Map<string, DayContent>();
- for (const day of calendarDays) {
- const key = formatDateToLocal(day);
- const inMonth = day.getMonth() === month;
- const dayNotes = inMonth ? findNotesForDate(notes, day) : [];
- contents.set(key, {
- layout: buildDayShiftLayout(
- inMonth ? (shiftsByDay.get(key) ?? []) : [],
- externalSyncs,
- { maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort }
- ),
- events: dayNotes.filter((n) => n.type === "event"),
- notes: dayNotes.filter((n) => n.type !== "event"),
- });
- }
- return contents;
+ return buildDayContents(
+ calendarDays,
+ shifts,
+ notes,
+ externalSyncs,
+ { maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort },
+ // Leading and trailing days of other months stay empty
+ (day) => day.getMonth() === month
+ );
}, [
calendarDays,
currentDate,
@@ -253,11 +203,6 @@ export function MonthGrid({
combinedSort,
]);
- const cancelPress = () => {
- if (pressTimer.current) clearTimeout(pressTimer.current);
- pressTimer.current = null;
- };
-
/**
* Day number, plus one counter per minimal-mode sync. Those carry no text, so
* the header row has space for them and the cell body keeps its full budget.
@@ -280,17 +225,7 @@ export function MonthGrid({
{content.layout.minimalGroups.length > 0 && (
<span className="ml-auto flex shrink-0 items-center gap-1">
{content.layout.minimalGroups.map(({ sync, shifts: synced }) => (
- <span
- key={sync.id}
- className="shift-chip flex shrink-0 items-center gap-1 rounded-[6px] px-[5px] py-0.5 dark:[--shift-tint:14%]"
- style={shiftVars(sync.color)}
- title={sync.name}
- >
- <RefreshCw className="size-3 shrink-0" />
- <span className="font-mono text-[11px] font-semibold leading-4">
- {synced.length}
- </span>
- </span>
+ <MinimalSyncCounter key={sync.id} sync={sync} count={synced.length} />
))}
</span>
)}
@@ -340,92 +275,25 @@ export function MonthGrid({
hiddenExternal > 0 && t("calendarView.externalCount", { count: hiddenExternal }),
].filter(Boolean);
- const chip =
- "shift-chip flex min-w-0 shrink-0 gap-1.5 rounded-[6px] py-0.5 pr-[7px] dark:[--shift-tint:14%]";
- const time = (shift: ShiftWithCalendar) => (
- <span className="shrink-0 whitespace-nowrap font-mono text-[10.5px] leading-4 opacity-75">
- {shift.isAllDay
- ? t("calendarView.allDayShort")
- : shift.segments?.length
- ? formatTimeRange(shift)
- : shift.startTime.slice(0, 5)}
- </span>
- );
-
return (
<>
{entries.slice(0, shown).map((entry) => {
switch (entry.kind) {
- case "shift": {
- const { shift } = entry;
+ case "shift":
return (
- <span
+ <ShiftChip
key={entry.key}
- className={cn(chip, "pl-[5px]")}
- style={shiftVars(shift.color)}
- title={`${shift.title}${shift.notes ? `\n${shift.notes}` : ""}`}
- >
- <span className="shift-rail w-[3px] shrink-0 self-stretch rounded-full" />
- <span className="min-w-0 flex-1">
- <span className="block truncate text-[11.5px] font-medium leading-4">
- {shift.title}
- </span>
- {showShiftNotes && shift.notes && (
- <span className="block truncate text-[10.5px] leading-[14px] opacity-75">
- {shift.notes}
- </span>
- )}
- </span>
- {signupBadge(shift)}
- {time(shift)}
- </span>
+ shift={entry.shift}
+ showNote={showShiftNotes}
+ signupsEnabled={signupsEnabled(entry.shift.calendarId)}
+ />
);
- }
case "external":
- // The sync icon takes the rail's place so imported entries stay recognisable
- return (
- <span
- key={entry.key}
- className={cn(chip, "items-center pl-[5px]")}
- style={shiftVars(entry.shift.color)}
- title={entry.shift.title}
- >
- <RefreshCw className="size-3 shrink-0" />
- <span className="min-w-0 flex-1 truncate text-[11.5px] font-medium leading-4">
- {entry.shift.title}
- </span>
- {time(entry.shift)}
- </span>
- );
+ return <ExternalShiftChip key={entry.key} shift={entry.shift} />;
case "event":
- return (
- <span
- key={entry.key}
- className="flex h-5 min-w-0 shrink-0 items-center gap-1.5 rounded-[6px] bg-cell-event px-[7px] shadow-[inset_0_0_0_1px_var(--cell-event-line)]"
- title={entry.note.note}
- >
- <CalendarClock
- className="shift-icon size-3 shrink-0"
- style={shiftVars(entry.note.color || undefined)}
- />
- <span className="min-w-0 flex-1 truncate text-[11.5px] font-medium text-cell-event-ink">
- {entry.note.note}
- </span>
- </span>
- );
+ return <EventChip key={entry.key} note={entry.note} />;
case "note":
- return (
- <span
- key={entry.key}
- className="flex h-[18px] min-w-0 shrink-0 items-center gap-1.5 px-1"
- title={entry.note.note}
- >
- <StickyNote className="size-3 shrink-0 text-cell-note" />
- <span className="min-w-0 flex-1 truncate text-[11.5px] text-fg-body dark:text-fg-secondary">
- {entry.note.note}
- </span>
- </span>
- );
+ return <NoteLine key={entry.key} note={entry.note} />;
}
})}
{overflow.length > 0 && (
@@ -570,7 +438,7 @@ export function MonthGrid({
style={shiftVars(shift.color)}
/>
<span className="min-w-0 flex-1 truncate">{shift.title}</span>
- {signupBadge(shift)}
+ <SignupBadge shift={shift} enabled={signupsEnabled(shift.calendarId)} />
</span>
))}
{minimalGroups.map(({ sync, shifts: syncShifts }) => (
@@ -643,6 +511,8 @@ export function MonthGrid({
<div
ref={gridRef}
+ onTouchStart={swipeHandlers?.onTouchStart}
+ onTouchEnd={swipeHandlers?.onTouchEnd}
className={cn(
"grid flex-1 grid-cols-7",
phone
@@ -671,27 +541,7 @@ export function MonthGrid({
disabled={toggling}
aria-pressed={selected}
aria-label={day.toLocaleDateString()}
- onClick={() => {
- if (longPressed.current) {
- longPressed.current = false;
- return;
- }
- onDayClick(day);
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- onDayContextMenu?.(day);
- }}
- onTouchStart={() => {
- longPressed.current = false;
- if (!onDayContextMenu) return;
- pressTimer.current = setTimeout(() => {
- longPressed.current = true;
- onDayContextMenu(day);
- }, LONG_PRESS_MS);
- }}
- onTouchEnd={cancelPress}
- onTouchMove={cancelPress}
+ {...dayPress(day)}
style={
highlighted ? ({ "--highlight": highlightColor } as React.CSSProperties) : undefined
}
diff --git a/components/segmented-control.tsx b/components/segmented-control.tsx
index 050bef7..c7f7e70 100644
--- a/components/segmented-control.tsx
+++ b/components/segmented-control.tsx
@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
interface SegmentedControlProps<T extends string> {
value: T;
onChange: (value: T) => void;
- options: { value: T; label: string; badge?: React.ReactNode }[];
+ options: { value: T; label: React.ReactNode; ariaLabel?: string; badge?: React.ReactNode }[];
label: string;
size?: "md" | "lg";
className?: string;
@@ -34,6 +34,8 @@ export function SegmentedControl<T extends string>({
type="button"
role="tab"
aria-selected={active}
+ aria-label={option.ariaLabel}
+ title={option.ariaLabel}
onClick={() => onChange(option.value)}
className={cn(
"flex flex-1 items-center justify-center gap-1.5 rounded-lg font-medium transition-colors",
diff --git a/components/shift-list-view.tsx b/components/shift-list-view.tsx
new file mode 100644
index 0000000..f5b1f18
--- /dev/null
+++ b/components/shift-list-view.tsx
@@ -0,0 +1,475 @@
+"use client";
+
+import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { endOfWeek, getISOWeek, isSameDay, isSameWeek, isToday, startOfWeek } from "date-fns";
+import { ArrowDownUp, Lock, RefreshCw, Search, X } from "lucide-react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
+import { formatDateToLocal, formatWeekRange } from "@/lib/date-utils";
+import {
+ ShiftSortOrder,
+ ShiftSortType,
+ formatHours,
+ getShiftMinutes,
+ shiftVars,
+} from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+import { ShiftDetailRow } from "@/components/day-detail";
+import {
+ EventChip,
+ NoteLine,
+ TODAY_BADGE,
+ buildDayContents,
+ useDayPress,
+} from "@/components/day-cell-entries";
+
+export interface ListSort {
+ type: ShiftSortType;
+ order: ShiftSortOrder;
+ /** The calendar pins its own view, so the personal sort would not apply */
+ locked: boolean;
+ onChange: (patch: { sortType?: ShiftSortType; sortOrder?: ShiftSortOrder }) => void;
+}
+
+interface ShiftListViewProps {
+ variant: "desktop" | "phone";
+ /** Every day of the visible month, so stamping by day click works on empty days too */
+ days: Date[];
+ selectedDay: Date;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+ presets: ShiftPreset[];
+ externalSyncs: ExternalSync[];
+ togglingDates: Set<string>;
+ sort: ListSort;
+ combinedSort: boolean;
+ highlightedWeekdays?: number[];
+ highlightColor?: string;
+ /** A preset is armed: clicking a shift row stamps the day instead of opening the shift */
+ stampArmed: boolean;
+ canEditShift: (shift: ShiftWithCalendar) => boolean;
+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;
+ onEditShift: (shift: ShiftWithCalendar) => void;
+ onDeleteShift: (shift: ShiftWithCalendar) => void;
+ onDayClick: (date: Date) => void;
+ /** Selection only: a shift-row click opens the shift and marks its day, but must not stamp */
+ onSelectDay: (date: Date) => void;
+ onDayContextMenu?: (date: Date) => void;
+ /** Bump `nonce` to scroll to `key` again */
+ scrollTarget?: { key: string; nonce: number } | null;
+}
+
+const NO_PRESET = "none";
+const WEEK = { weekStartsOn: 1 } as const;
+const noop = () => undefined;
+
+/** Filter chip a shift falls under: its sync, its preset, or "without preset". */
+function chipKeyOf(shift: ShiftWithCalendar, presetIds: Set<string>): string {
+ if (shift.syncedFromExternal && shift.externalSyncId) return `sync:${shift.externalSyncId}`;
+ return shift.presetId && presetIds.has(shift.presetId) ? `preset:${shift.presetId}` : NO_PRESET;
+}
+
+export function ShiftListView({
+ variant,
+ days,
+ selectedDay,
+ shifts,
+ notes,
+ presets,
+ externalSyncs,
+ togglingDates,
+ sort,
+ combinedSort,
+ highlightedWeekdays = [],
+ highlightColor,
+ stampArmed,
+ canEditShift,
+ canDeleteShift,
+ onEditShift,
+ onDeleteShift,
+ onDayClick,
+ onSelectDay,
+ onDayContextMenu,
+ scrollTarget,
+}: ShiftListViewProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const desktop = variant === "desktop";
+ const dayPress = useDayPress(onDayClick, onDayContextMenu);
+ const [query, setQuery] = useState("");
+ const [activeChips, setActiveChips] = useState<string[]>([]);
+ const scroller = useRef<HTMLDivElement>(null);
+
+ // A jump would land nowhere if search or chips hid its day, so a new target drops
+ // them first. Adjusted during render per React's "state from props" pattern.
+ const jumpNonce = scrollTarget?.nonce ?? 0;
+ const [prevJumpNonce, setPrevJumpNonce] = useState(jumpNonce);
+ if (jumpNonce !== prevJumpNonce) {
+ setPrevJumpNonce(jumpNonce);
+ setQuery("");
+ setActiveChips([]);
+ }
+
+ const weekdayFormat = useMemo(() => new Intl.DateTimeFormat(locale, { weekday: "short" }), [locale]);
+ const presetIds = useMemo(() => new Set(presets.map((p) => p.id)), [presets]);
+
+ // "minimal" syncs are listed in full here: the list is where details live
+ const listSyncs = useMemo(
+ () => externalSyncs.map((sync) => ({ ...sync, displayMode: "normal" as const })),
+ [externalSyncs]
+ );
+ const contents = useMemo(
+ () =>
+ buildDayContents(
+ days,
+ shifts,
+ notes,
+ listSyncs,
+ { sortType: sort.type, sortOrder: sort.order, combinedSort },
+ () => true
+ ),
+ [days, shifts, notes, listSyncs, sort.type, sort.order, combinedSort]
+ );
+
+ const chips = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const content of contents.values()) {
+ for (const shift of content.layout.visible) {
+ const key = chipKeyOf(shift, presetIds);
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+ const result: { key: string; label: string; color?: string; count: number; synced?: boolean }[] = [];
+ for (const preset of presets) {
+ const count = counts.get(`preset:${preset.id}`);
+ if (count) result.push({ key: `preset:${preset.id}`, label: preset.title, color: preset.color, count });
+ }
+ const none = counts.get(NO_PRESET);
+ if (none) result.push({ key: NO_PRESET, label: t("calendarView.listWithoutPreset"), count: none });
+ for (const sync of externalSyncs) {
+ const count = counts.get(`sync:${sync.id}`);
+ if (count) result.push({ key: `sync:${sync.id}`, label: sync.name, color: sync.color, count, synced: true });
+ }
+ return result;
+ }, [contents, presets, presetIds, externalSyncs, t]);
+
+ // A chip can vanish with its last shift or a month change; ignore stale selections
+ const effectiveChips = useMemo(() => {
+ const known = new Set(chips.map((c) => c.key));
+ return activeChips.filter((key) => known.has(key));
+ }, [chips, activeChips]);
+ const chipFilterKey = effectiveChips.join("|");
+ const needle = query.trim().toLocaleLowerCase(locale);
+ const filtering = needle.length > 0 || chipFilterKey.length > 0;
+
+ const weeks = useMemo(() => {
+ const active = new Set(chipFilterKey ? chipFilterKey.split("|") : []);
+ const filtered = needle.length > 0 || active.size > 0;
+ const matches = (text: string | null | undefined) =>
+ !!text && text.toLocaleLowerCase(locale).includes(needle);
+ const groups: {
+ key: string;
+ start: Date;
+ days: { day: Date; key: string; shifts: ShiftWithCalendar[]; events: CalendarNote[]; notes: CalendarNote[] }[];
+ }[] = [];
+
+ for (const day of days) {
+ const key = formatDateToLocal(day);
+ const content = contents.get(key)!;
+ const dayShifts = content.layout.visible.filter(
+ (shift) =>
+ (active.size === 0 || active.has(chipKeyOf(shift, presetIds))) &&
+ (!needle || matches(shift.title) || matches(shift.notes))
+ );
+ // Notes never match a preset filter; with a search they must match it
+ const showNotes = active.size === 0;
+ const keepNote = (note: CalendarNote) => showNotes && (!needle || matches(note.note));
+ const events = content.events.filter(keepNote);
+ const dayNotes = content.notes.filter(keepNote);
+ if (filtered && dayShifts.length + events.length + dayNotes.length === 0) continue;
+
+ const start = startOfWeek(day, WEEK);
+ const weekKey = formatDateToLocal(start);
+ let group = groups[groups.length - 1];
+ if (!group || group.key !== weekKey) {
+ group = { key: weekKey, start, days: [] };
+ groups.push(group);
+ }
+ group.days.push({ day, key, shifts: dayShifts, events, notes: dayNotes });
+ }
+ return groups;
+ }, [days, contents, presetIds, needle, chipFilterKey, locale]);
+
+ const scrollToKey = (key: string) => {
+ const container = scroller.current;
+ if (!container) return;
+ const row = key ? container.querySelector<HTMLElement>(`[data-day="${key}"]`) : null;
+ // 32px keeps the row clear of the sticky week header
+ container.scrollTop = row ? Math.max(0, row.offsetTop - 32) : 0;
+ };
+
+ const monthKey = days.length > 0 ? formatDateToLocal(days[0]) : "";
+ const scrollToFocus = useEffectEvent(() => {
+ const todayKey = formatDateToLocal(new Date());
+ const selectedKey = formatDateToLocal(selectedDay);
+ const inMonth = (key: string) => days.some((d) => formatDateToLocal(d) === key);
+ scrollToKey(inMonth(todayKey) ? todayKey : inMonth(selectedKey) ? selectedKey : "");
+ });
+ useEffect(() => {
+ scrollToFocus();
+ }, [monthKey]);
+
+ const jumpTo = useEffectEvent((key: string) => scrollToKey(key));
+ useEffect(() => {
+ if (scrollTarget) jumpTo(scrollTarget.key);
+ }, [scrollTarget]);
+
+ const toggleChip = (key: string) =>
+ setActiveChips((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]));
+
+ const sortLabels: Record<ShiftSortType, string> = {
+ startTime: t("view.sortByStartTime"),
+ createdAt: t("view.sortByCreatedAt"),
+ title: t("view.sortByTitle"),
+ };
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div
+ className={cn(
+ "flex shrink-0 flex-col gap-2 border-b border-line",
+ desktop ? "px-[18px] pb-2.5 pt-3.5" : "px-3.5 pb-2.5"
+ )}
+ >
+ <div className="flex items-center gap-2">
+ {/* Not a <label>: the clear button would become the label's control */}
+ <div className="relative min-w-0 flex-1">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-fg-tertiary" />
+ <input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t("calendarView.listSearchPlaceholder")}
+ aria-label={t("calendarView.listSearchPlaceholder")}
+ className="h-9 w-full rounded-lg border border-line bg-surface-card pl-8 pr-8 text-[13.5px] text-fg-strong outline-none placeholder:text-fg-faint focus-visible:border-brand-dot [&::-webkit-search-cancel-button]:hidden"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => setQuery("")}
+ aria-label={t("calendarView.listClearSearch")}
+ className="absolute right-1.5 top-1/2 flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-sunken"
+ >
+ <X className="size-3.5" />
+ </button>
+ )}
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={sort.locked}
+ title={sort.locked ? t("calendarView.listSortPinnedHint") : t("view.sortOptions")}
+ aria-label={t("view.sortOptions")}
+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-lg border border-line px-2.5 text-[13px] font-medium text-fg-secondary transition-colors hover:bg-surface-panel disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {sort.locked ? <Lock className="size-3.5" /> : <ArrowDownUp className="size-4" />}
+ {desktop && sortLabels[sort.type]}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>{t("view.sortBy")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sort.type}
+ onValueChange={(value) => sort.onChange({ sortType: value as ShiftSortType })}
+ >
+ {(Object.keys(sortLabels) as ShiftSortType[]).map((type) => (
+ <DropdownMenuRadioItem key={type} value={type}>
+ {sortLabels[type]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{t("view.sortOrder")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sort.order}
+ onValueChange={(value) => sort.onChange({ sortOrder: value as ShiftSortOrder })}
+ >
+ <DropdownMenuRadioItem value="asc">{t("view.sortOrderAsc")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="desc">{t("view.sortOrderDesc")}</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ {chips.length > 0 && (
+ <div className="-mx-1 flex gap-1.5 overflow-x-auto px-1 pb-0.5 [scrollbar-width:none]">
+ {chips.map((chip) => {
+ const active = effectiveChips.includes(chip.key);
+ return (
+ <button
+ key={chip.key}
+ type="button"
+ aria-pressed={active}
+ onClick={() => toggleChip(chip.key)}
+ className={cn(
+ "flex h-7 shrink-0 items-center gap-1.5 rounded-full border px-2.5 text-[12.5px] font-medium transition-colors",
+ active
+ ? "border-transparent bg-brand-soft text-brand-ink"
+ : "border-line text-fg-secondary hover:bg-surface-panel"
+ )}
+ >
+ {chip.synced ? (
+ <RefreshCw className="size-3 shrink-0" />
+ ) : chip.color ? (
+ <span className="shift-rail size-2 shrink-0 rounded-full" style={shiftVars(chip.color)} />
+ ) : null}
+ <span className="max-w-[180px] truncate">{chip.label}</span>
+ <span className="font-mono text-[11px] opacity-70">{chip.count}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* pb-16: the floating StampDock overlays the bottom of the scroller */}
+ <div
+ ref={scroller}
+ className={cn("relative min-h-0 flex-1 overflow-y-auto", desktop ? "px-[18px] pb-16" : "px-2")}
+ >
+ {weeks.length === 0 ? (
+ <p className="py-10 text-center text-[13px] text-fg-tertiary">
+ {filtering ? t("calendarView.listNoMatches") : t("shift.noShiftsInMonth")}
+ </p>
+ ) : (
+ weeks.map((week) => (
+ <section key={week.key}>
+ <h2 className="sticky top-0 z-10 flex items-baseline gap-2 bg-background py-1.5 pl-1 text-[11.5px] font-semibold uppercase tracking-[0.06em] text-fg-tertiary">
+ {isSameWeek(week.start, new Date(), WEEK) ? (
+ <span className="text-brand-ink">{t("calendarView.thisWeek")}</span>
+ ) : (
+ t("calendarView.calendarWeek", { week: getISOWeek(week.start) })
+ )}
+ <span className="font-mono font-normal normal-case tracking-normal text-fg-faint">
+ {formatWeekRange(week.start, endOfWeek(week.start, WEEK), locale, false)}
+ </span>
+ </h2>
+ {week.days.map(({ day, key, shifts: dayShifts, events, notes: dayNotes }) => {
+ const today = isToday(day);
+ const selected = isSameDay(day, selectedDay);
+ const weekend = day.getDay() === 0 || day.getDay() === 6;
+ const highlighted = !!highlightColor && highlightedWeekdays.includes(day.getDay());
+ const toggling = togglingDates.has(key);
+ const minutes = dayShifts.reduce((sum, s) => sum + getShiftMinutes(s), 0);
+ const empty = dayShifts.length + events.length + dayNotes.length === 0;
+ const press = dayPress(day);
+
+ return (
+ // Buttons must not nest: the gutter is the real control, the row forwards mouse clicks
+ <div
+ key={key}
+ // Scroll targets are looked up by this attribute instead of a ref map
+ data-day={key}
+ onClick={toggling ? undefined : press.onClick}
+ onContextMenu={press.onContextMenu}
+ onTouchStart={press.onTouchStart}
+ onTouchEnd={press.onTouchEnd}
+ onTouchMove={press.onTouchMove}
+ style={highlighted ? ({ "--highlight": highlightColor } as React.CSSProperties) : undefined}
+ className={cn(
+ "flex cursor-pointer items-stretch gap-3 rounded-[10px] border-b border-line px-1.5 transition-colors [-webkit-touch-callout:none]",
+ empty ? "py-1.5" : "py-2.5",
+ selected ? "bg-cell-selected" : "hover:bg-surface-panel",
+ highlighted && "day-highlight",
+ toggling && "cursor-wait opacity-60"
+ )}
+ >
+ <button
+ type="button"
+ disabled={toggling}
+ aria-pressed={selected}
+ aria-label={day.toLocaleDateString()}
+ // The row's handler runs through bubbling; this only needs to be focusable
+ className="flex w-11 shrink-0 flex-col items-center gap-0.5 rounded-md pt-0.5 outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]"
+ >
+ <span className="text-[10.5px] font-semibold uppercase tracking-[0.06em] text-cell-muted">
+ {weekdayFormat.format(day)}
+ </span>
+ <span
+ className={cn(
+ "inline-flex size-[26px] items-center justify-center rounded-full font-mono text-[14px] leading-none",
+ today ? TODAY_BADGE : weekend ? "text-cell-weekend-num" : "text-fg-body"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ </button>
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ {empty ? (
+ <span className="flex h-full items-center text-[12.5px] text-fg-faint">
+ {t("calendarView.dayFree")}
+ </span>
+ ) : (
+ <>
+ {dayShifts.length > 0 && (
+ <span className="font-mono text-[11.5px] text-fg-tertiary">
+ {t("calendarView.shiftCount", { count: dayShifts.length })}
+ {minutes > 0 && ` · ${formatHours(minutes, locale)}`}
+ </span>
+ )}
+ {dayShifts.length > 0 && (
+ // Unarmed, a click opens the shift; armed, it bubbles up to stamp instead.
+ // The long press stays on the day's own chrome, or it would open two sheets.
+ <div
+ className="flex flex-col gap-1.5"
+ onClick={(e) => {
+ if (stampArmed) return;
+ e.stopPropagation();
+ onSelectDay(day);
+ }}
+ onTouchStart={(e) => {
+ if (!stampArmed) e.stopPropagation();
+ }}
+ >
+ {dayShifts.map((shift) => (
+ <ShiftDetailRow
+ key={shift.id}
+ shift={shift}
+ fullTitle
+ canEdit={canEditShift(shift)}
+ canDelete={canDeleteShift(shift)}
+ actions="menu"
+ onEdit={onEditShift}
+ // Armed, the click must reach the row above and stamp instead
+ onOpen={stampArmed ? noop : onEditShift}
+ onDelete={onDeleteShift}
+ />
+ ))}
+ </div>
+ )}
+ {events.map((note) => (
+ <EventChip key={note.id} note={note} wrap />
+ ))}
+ {dayNotes.map((note) => (
+ <NoteLine key={note.id} note={note} wrap />
+ ))}
+ </>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </section>
+ ))
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/components/themed-toaster.tsx b/components/themed-toaster.tsx
index 79e6c0d..aade3cf 100644
--- a/components/themed-toaster.tsx
+++ b/components/themed-toaster.tsx
@@ -2,13 +2,16 @@
import { Toaster } from "sonner";
import { useTheme } from "next-themes";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
export function ThemedToaster() {
const { theme } = useTheme();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
return (
<Toaster
- position="top-center"
+ // On mobile the view-mode switcher and month/week arrows sit in the top row too
+ position={desktop ? "top-center" : "bottom-center"}
closeButton
theme={theme as "light" | "dark" | "system"}
toastOptions={{
diff --git a/components/view-mode-switcher.tsx b/components/view-mode-switcher.tsx
new file mode 100644
index 0000000..298c45a
--- /dev/null
+++ b/components/view-mode-switcher.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { CalendarDays, Columns3, List } from "lucide-react";
+import { SegmentedControl } from "@/components/segmented-control";
+import { AVAILABLE_VIEW_MODES, CalendarViewMode } from "@/hooks/useCalendarViewMode";
+
+const ICONS = { month: CalendarDays, week: Columns3, list: List } as const;
+
+export function ViewModeSwitcher({
+ value,
+ onChange,
+ variant,
+}: {
+ value: CalendarViewMode;
+ onChange: (mode: CalendarViewMode) => void;
+ /** "icon" is the phone title row, where three words do not fit */
+ variant: "text" | "icon";
+}) {
+ const t = useTranslations();
+
+ const labels: Record<CalendarViewMode, string> = {
+ month: t("calendarView.viewMonth"),
+ week: t("calendarView.viewWeek"),
+ list: t("calendarView.viewList"),
+ };
+
+ return (
+ <SegmentedControl<CalendarViewMode>
+ label={t("calendarView.viewMode")}
+ value={value}
+ onChange={onChange}
+ // Icon track: 36px per segment plus the 6px track padding
+ className={variant === "icon" ? "w-[114px] shrink-0" : "shrink-0"}
+ options={AVAILABLE_VIEW_MODES.map((mode) => {
+ const Icon = ICONS[mode];
+ return variant === "icon"
+ ? { value: mode, label: <Icon className="size-4" />, ariaLabel: labels[mode] }
+ : { value: mode, label: <span className="px-3">{labels[mode]}</span> };
+ })}
+ />
+ );
+}
diff --git a/components/week-grid.tsx b/components/week-grid.tsx
new file mode 100644
index 0000000..68da7fd
--- /dev/null
+++ b/components/week-grid.tsx
@@ -0,0 +1,242 @@
+"use client";
+
+import { useMemo } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { isSameDay, isToday } from "date-fns";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
+import { formatDateToLocal } from "@/lib/date-utils";
+import { DayLayoutOptions } from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+import {
+ DayContent,
+ EventChip,
+ ExternalShiftChip,
+ MinimalSyncCounter,
+ NoteLine,
+ ShiftChip,
+ TODAY_BADGE,
+ buildDayContents,
+ useDayPress,
+ useSignupsEnabled,
+} from "@/components/day-cell-entries";
+
+interface WeekGridProps {
+ variant: "desktop" | "phone";
+ /** Monday to Sunday */
+ days: Date[];
+ selectedDay: Date;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+ externalSyncs: ExternalSync[];
+ togglingDates: Set<string>;
+ layout: DayLayoutOptions;
+ showShiftNotes?: boolean;
+ highlightedWeekdays?: number[];
+ highlightColor?: string;
+ onDayClick: (date: Date) => void;
+ onDayContextMenu?: (date: Date) => void;
+ /** Phone only: swipe left/right across the grid to step the week */
+ swipeHandlers?: {
+ onTouchStart: (e: React.TouchEvent) => void;
+ onTouchEnd: (e: React.TouchEvent) => void;
+ };
+}
+
+export function WeekGrid({
+ variant,
+ days,
+ selectedDay,
+ shifts,
+ notes,
+ externalSyncs,
+ togglingDates,
+ layout,
+ showShiftNotes = false,
+ highlightedWeekdays = [],
+ highlightColor,
+ onDayClick,
+ onDayContextMenu,
+ swipeHandlers,
+}: WeekGridProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const signupsEnabled = useSignupsEnabled();
+ const dayPress = useDayPress(onDayClick, onDayContextMenu);
+ const desktop = variant === "desktop";
+
+ const { sortType, sortOrder, combinedSort } = layout;
+ // The per-day caps exist to fit month cells; a week day shows everything
+ const contents = useMemo(
+ () =>
+ buildDayContents(
+ days,
+ shifts,
+ notes,
+ externalSyncs,
+ { sortType, sortOrder, combinedSort },
+ () => true
+ ),
+ [days, shifts, notes, externalSyncs, sortType, sortOrder, combinedSort]
+ );
+
+ const formatters = useMemo(
+ () => ({
+ weekday: new Intl.DateTimeFormat(locale, { weekday: desktop ? "long" : "short" }),
+ month: new Intl.DateTimeFormat(locale, { month: "short" }),
+ }),
+ [locale, desktop]
+ );
+ const straddlesMonths = days.length > 0 && days[0].getMonth() !== days[days.length - 1].getMonth();
+
+ const renderEntries = (content: DayContent) => (
+ <>
+ {content.layout.visible.map((shift) =>
+ shift.syncedFromExternal ? (
+ <ExternalShiftChip key={shift.id} shift={shift} wrap />
+ ) : (
+ <ShiftChip
+ key={shift.id}
+ shift={shift}
+ showNote={showShiftNotes}
+ signupsEnabled={signupsEnabled(shift.calendarId)}
+ interactive
+ wrap
+ />
+ )
+ )}
+ {content.events.map((note) => (
+ <EventChip key={note.id} note={note} wrap />
+ ))}
+ {content.notes.map((note) => (
+ <NoteLine key={note.id} note={note} wrap />
+ ))}
+ </>
+ );
+
+ const isEmpty = (content: DayContent) =>
+ content.layout.visible.length === 0 &&
+ content.layout.minimalGroups.length === 0 &&
+ content.events.length === 0 &&
+ content.notes.length === 0;
+
+ return (
+ <div
+ onTouchStart={swipeHandlers?.onTouchStart}
+ onTouchEnd={swipeHandlers?.onTouchEnd}
+ className={cn(
+ desktop
+ ? "mx-[18px] mt-3.5 grid min-h-0 flex-1 grid-cols-7 gap-px border-y border-line bg-line-grid"
+ : "flex flex-col px-2"
+ )}
+ >
+ {days.map((day) => {
+ const key = formatDateToLocal(day);
+ const content = contents.get(key)!;
+ const today = isToday(day);
+ const selected = isSameDay(day, selectedDay);
+ const weekend = day.getDay() === 0 || day.getDay() === 6;
+ const highlighted = !!highlightColor && highlightedWeekdays.includes(day.getDay());
+ const toggling = togglingDates.has(key);
+
+ const counters = content.layout.minimalGroups.map(({ sync, shifts: synced }) => (
+ <MinimalSyncCounter key={sync.id} sync={sync} count={synced.length} />
+ ));
+
+ const press = dayPress(day);
+
+ return (
+ // A shift chip's own self-assign button must not nest inside another button,
+ // so the cell forwards clicks itself and only the day badge stays focusable.
+ <div
+ key={key}
+ onClick={toggling ? undefined : press.onClick}
+ onContextMenu={press.onContextMenu}
+ onTouchStart={press.onTouchStart}
+ onTouchEnd={press.onTouchEnd}
+ onTouchMove={press.onTouchMove}
+ style={highlighted ? ({ "--highlight": highlightColor } as React.CSSProperties) : undefined}
+ className={cn(
+ "relative min-w-0 select-none text-left transition-colors [-webkit-touch-callout:none]",
+ desktop
+ ? cn(
+ // pb-16: the floating StampDock overlays the bottom of the column, each of which scrolls on its own
+ "flex min-h-0 flex-col items-stretch gap-[3px] overflow-y-auto px-2 pb-16",
+ weekend ? "bg-surface-weekend" : "bg-surface-cell",
+ "hover:bg-surface-panel",
+ selected && "shadow-[inset_0_0_0_1.5px_var(--brand-dot)]"
+ )
+ : cn(
+ "flex items-start gap-3 rounded-[10px] px-1.5 py-2.5",
+ selected && "bg-cell-selected"
+ ),
+ highlighted && "day-highlight",
+ toggling && "cursor-wait opacity-60"
+ )}
+ >
+ {desktop ? (
+ <>
+ {/* Not sticky: day-highlight paints a background-image, which bg-inherit can't carry */}
+ <span className="-mx-2 flex shrink-0 items-center gap-1.5 px-2 pb-1.5 pt-2">
+ <button
+ type="button"
+ disabled={toggling}
+ aria-pressed={selected}
+ aria-label={day.toLocaleDateString()}
+ className={cn(
+ "inline-flex h-[22px] min-w-[22px] shrink-0 items-center justify-center rounded-full px-1 font-mono text-[12.5px] font-medium leading-none outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]",
+ today ? TODAY_BADGE : "text-fg-body dark:text-fg-secondary"
+ )}
+ >
+ {day.getDate()}
+ </button>
+ <span className="min-w-0 truncate text-[11.5px] font-semibold uppercase tracking-[0.06em] text-fg-tertiary">
+ {formatters.weekday.format(day)}
+ {straddlesMonths && ` · ${formatters.month.format(day)}`}
+ </span>
+ {counters.length > 0 && (
+ <span className="ml-auto flex shrink-0 items-center gap-1">{counters}</span>
+ )}
+ </span>
+ {renderEntries(content)}
+ </>
+ ) : (
+ <>
+ <button
+ type="button"
+ disabled={toggling}
+ aria-pressed={selected}
+ aria-label={day.toLocaleDateString()}
+ className="flex w-10 shrink-0 flex-col items-center gap-0.5 rounded-md pt-0.5 outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]"
+ >
+ <span className="text-[10.5px] font-semibold uppercase tracking-[0.06em] text-cell-muted">
+ {formatters.weekday.format(day)}
+ </span>
+ <span
+ className={cn(
+ "inline-flex size-[26px] items-center justify-center rounded-full font-mono text-[14px] leading-none",
+ today
+ ? TODAY_BADGE
+ : weekend
+ ? "font-[450] text-cell-weekend-num"
+ : "font-[450] text-fg-body"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ </button>
+ <span className="flex min-w-0 flex-1 flex-col gap-1 border-b border-line pb-2.5">
+ {counters.length > 0 && <span className="flex flex-wrap gap-1">{counters}</span>}
+ {renderEntries(content)}
+ {isEmpty(content) && (
+ <span className="py-1 text-[12.5px] text-fg-faint">{t("calendarView.dayFree")}</span>
+ )}
+ </span>
+ </>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/docs/superpowers/plans/2026-09-17-calendar-view-modes.md b/docs/superpowers/plans/2026-09-17-calendar-view-modes.md
new file mode 100644
index 0000000..2a65632
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-17-calendar-view-modes.md
@@ -0,0 +1,1921 @@
+# Calendar View Modes (Month / Week / List) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Add a week view and a list view next to the month grid, switched through a Month/Week/List control in the header (issues #184, #185, #186).
+
+**Architecture:** One per-device mode (`localStorage`) owned by `app/page.tsx`; `currentDate` stays the single date anchor and the stepper steps by month or week. `CalendarWorkspace` renders `MonthGrid`, a new `WeekGrid` or a new `ShiftListView` from the same already-loaded data. Cell entry renderers move out of `MonthGrid` into a shared module so the week view reuses them. No schema, API or fetching change.
+
+**Tech Stack:** Next.js 16 (App Router), React 19.3 (`useSyncExternalStore`, `useEffectEvent`), date-fns 4, next-intl, Tailwind v4, lucide-react.
+
+**Spec:** `docs/superpowers/specs/2026-09-17-calendar-view-modes-design.md`
+
+## Global Constraints
+
+- Branch `feat/calendar-view-modes` (already created from `origin/main`). Conventional Commits; **no Claude attribution** in commit messages.
+- Code comments English, one or two lines, only where a reader would otherwise break something. UI strings live in `messages/*.json`.
+- i18n: add keys to `messages/de.json` first, then mirror into `en`, `es`, `fr`, `it`, `cs`. `npm run i18n` fails on keys that are missing **or unused**, so a task adds exactly the keys its code references and removes keys it orphans.
+- Dates are local `YYYY-MM-DD`; use `formatDateToLocal` / `parseLocalDate` from `lib/date-utils.ts`, never `toISOString()`.
+- Weeks start on Monday: always `{ weekStartsOn: 1 }`.
+- `components/ui/*` are generated shadcn primitives — do not edit. `components/segmented-control.tsx` is a project component and may be edited.
+- `buildDayShiftLayout` treats `undefined` (not `null`) as "no per-day cap".
+- There is no unit-test framework. The gate per task is `npx tsc --noEmit && npm run lint && npm run i18n`; the Bash tool's Node version warning is a known non-issue.
+- Compare mode (`components/compare-workspace.tsx`) must keep working unchanged: `MonthStepper` / `MonthArrows` defaults stay month-stepping.
+
+## File Structure
+
+| File | Responsibility |
+|---|---|
+| `hooks/useCalendarViewMode.ts` (new) | persisted mode + list of modes that have a surface |
+| `lib/calendar-utils.ts` | `getWeekDays`, `getMonthDays` next to `getCalendarDays` |
+| `lib/date-utils.ts` | `formatWeekRange`, `formatPeriodCaption` |
+| `components/segmented-control.tsx` | option label may be a node, optional `ariaLabel` |
+| `components/view-mode-switcher.tsx` (new) | the Month/Week/List control, text or icon variant |
+| `components/app-header.tsx` | `step` on stepper/arrows, switcher in the desktop row |
+| `components/day-cell-entries.tsx` (new) | shared chips, `useDayPress`, `buildDayContents` |
+| `components/month-grid.tsx` | consumes the shared module, otherwise unchanged |
+| `components/week-grid.tsx` (new) | week view, desktop columns / phone rows |
+| `components/shift-list-view.tsx` (new) | list view with toolbar, week groups, day rows |
+| `components/day-detail.tsx` | `ShiftDetailRow` gets `fullTitle` |
+| `components/mobile-day-sheet.tsx` | footer list variant (next shift), `onShowList` |
+| `components/day-inspector.tsx` | `DayActions.onShowList?` replaces `onOpenMonthShifts` |
+| `components/calendar-workspace.tsx` | picks the surface by `viewMode`, mobile title row |
+| `components/month-dialogs.tsx`, `components/dialog-manager.tsx`, `hooks/useDialogStates.ts` | `MonthShiftsDialog` removed |
+| `app/page.tsx` | mode state, mode-aware date handlers, wiring |
+
+---
+
+### Task 1: Mode state, week-aware stepper and the switcher (#186)
+
+**Files:**
+- Create: `hooks/useCalendarViewMode.ts`, `components/view-mode-switcher.tsx`
+- Modify: `lib/calendar-utils.ts`, `lib/date-utils.ts`, `components/segmented-control.tsx`, `components/app-header.tsx`, `components/calendar-workspace.tsx`, `app/page.tsx`, `messages/{de,en,es,fr,it,cs}.json`
+
+**Interfaces:**
+- Produces:
+ - `type CalendarViewMode = "month" | "week" | "list"`; `AVAILABLE_VIEW_MODES: readonly CalendarViewMode[]`; `useCalendarViewMode(): readonly [CalendarViewMode, (mode: CalendarViewMode) => void]`
+ - `getWeekDays(date: Date): Date[]`, `getMonthDays(date: Date): Date[]`
+ - `type PeriodStep = "month" | "week"`; `formatWeekRange(start: Date, end: Date, locale: string, withYear?: boolean): string`; `formatPeriodCaption(date: Date, step: PeriodStep, locale: string, options?: { compact?: boolean }): string`
+ - `MonthStepper` / `MonthArrows` prop `step?: PeriodStep`
+ - `<ViewModeSwitcher value onChange variant="text" | "icon" />`
+ - `CalendarWorkspace` props `viewMode: CalendarViewMode`, `onViewModeChange: (mode: CalendarViewMode) => void`
+ - `AppHeader` props `viewMode?: CalendarViewMode`, `onViewModeChange?: (mode: CalendarViewMode) => void`
+
+- [ ] **Step 1: `lib/calendar-utils.ts` — add the two day generators below `getCalendarDays`**
+
+```ts
+export function getWeekDays(date: Date): Date[] {
+ return eachDayOfInterval({
+ start: startOfWeek(date, { weekStartsOn: 1 }),
+ end: endOfWeek(date, { weekStartsOn: 1 }),
+ });
+}
+
+export function getMonthDays(date: Date): Date[] {
+ return eachDayOfInterval({ start: startOfMonth(date), end: endOfMonth(date) });
+}
+```
+
+- [ ] **Step 2: `lib/date-utils.ts` — add the caption helpers after `formatLongDate`**
+
+Add imports at the top of the file: `import { endOfWeek, format, startOfWeek } from "date-fns";` and `import { getDateLocale } from "@/lib/locales";`.
+
+```ts
+export type PeriodStep = "month" | "week";
+
+const weekRangeFormatters = new Map<string, Intl.DateTimeFormat>();
+
+/** "8.–14. Sep. 2026"; formatRange collapses the parts both ends share. */
+export function formatWeekRange(start: Date, end: Date, locale: string, withYear = true): string {
+ const key = `${locale}|${withYear}`;
+ let formatter = weekRangeFormatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(locale, {
+ day: "numeric",
+ month: "short",
+ ...(withYear ? { year: "numeric" as const } : {}),
+ });
+ weekRangeFormatters.set(key, formatter);
+ }
+ return formatter.formatRange(start, end);
+}
+
+/** Stepper and title caption: the month name, or the Monday–Sunday range around `date`. */
+export function formatPeriodCaption(
+ date: Date,
+ step: PeriodStep,
+ locale: string,
+ { compact = false }: { compact?: boolean } = {}
+): string {
+ if (step === "month") return format(date, "LLLL yyyy", { locale: getDateLocale(locale) });
+ const start = startOfWeek(date, { weekStartsOn: 1 });
+ const end = endOfWeek(date, { weekStartsOn: 1 });
+ // Compact drops the year while the whole week lies in the current one
+ const thisYear = new Date().getFullYear();
+ const withYear =
+ !compact || start.getFullYear() !== thisYear || end.getFullYear() !== thisYear;
+ return formatWeekRange(start, end, locale, withYear);
+}
+```
+
+Before adding the `getDateLocale` import, run `grep -n "date-utils" lib/locales.ts`; if `lib/locales.ts` imports from `lib/date-utils.ts` (it should not), put both helpers into `lib/calendar-utils.ts` instead and adjust every import in this plan accordingly.
+
+- [ ] **Step 3: Create `hooks/useCalendarViewMode.ts`**
+
+```ts
+"use client";
+
+import { useCallback, useSyncExternalStore } from "react";
+
+export type CalendarViewMode = "month" | "week" | "list";
+
+/** Modes that have a surface; the switcher offers exactly these. */
+export const AVAILABLE_VIEW_MODES: readonly CalendarViewMode[] = ["month"];
+
+// Per-device like the view-setting keys in useViewSettings.ts, never synced to the account
+const STORAGE_KEY = "calendar-view-mode";
+const CHANGE_EVENT = "calendar-view-mode-change";
+
+// Keeps the choice for the session when storage is unavailable (private mode)
+let memory: CalendarViewMode | null = null;
+
+function readMode(): CalendarViewMode {
+ if (memory) return memory;
+ try {
+ const stored = window.localStorage.getItem(STORAGE_KEY) as CalendarViewMode | null;
+ return stored && AVAILABLE_VIEW_MODES.includes(stored) ? stored : "month";
+ } catch {
+ return "month";
+ }
+}
+
+function subscribe(onChange: () => void) {
+ window.addEventListener("storage", onChange);
+ window.addEventListener(CHANGE_EVENT, onChange);
+ return () => {
+ window.removeEventListener("storage", onChange);
+ window.removeEventListener(CHANGE_EVENT, onChange);
+ };
+}
+
+export function useCalendarViewMode() {
+ // The server snapshot keeps the first client render identical to SSR
+ const mode = useSyncExternalStore(subscribe, readMode, () => "month" as const);
+ const setMode = useCallback((next: CalendarViewMode) => {
+ memory = next;
+ try {
+ window.localStorage.setItem(STORAGE_KEY, next);
+ } catch {
+ // The in-memory value above still applies
+ }
+ window.dispatchEvent(new Event(CHANGE_EVENT));
+ }, []);
+ return [mode, setMode] as const;
+}
+```
+
+- [ ] **Step 4: `components/segmented-control.tsx` — allow node labels**
+
+Change the options type and the button:
+
+```tsx
+ options: { value: T; label: React.ReactNode; ariaLabel?: string; badge?: React.ReactNode }[];
+```
+
+```tsx
+ <button
+ key={option.value}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ aria-label={option.ariaLabel}
+ title={option.ariaLabel}
+ onClick={() => onChange(option.value)}
+```
+
+Everything else in the file stays. Existing call sites pass strings and keep compiling.
+
+- [ ] **Step 5: Create `components/view-mode-switcher.tsx`**
+
+```tsx
+"use client";
+
+import { useTranslations } from "next-intl";
+import { CalendarDays, CalendarRange, List } from "lucide-react";
+import { SegmentedControl } from "@/components/segmented-control";
+import { AVAILABLE_VIEW_MODES, CalendarViewMode } from "@/hooks/useCalendarViewMode";
+
+const ICONS = { month: CalendarDays, week: CalendarRange, list: List } as const;
+
+export function ViewModeSwitcher({
+ value,
+ onChange,
+ variant,
+}: {
+ value: CalendarViewMode;
+ onChange: (mode: CalendarViewMode) => void;
+ /** "icon" is the phone title row, where three words do not fit */
+ variant: "text" | "icon";
+}) {
+ const t = useTranslations();
+ if (AVAILABLE_VIEW_MODES.length < 2) return null;
+
+ const labels: Record<CalendarViewMode, string> = {
+ month: t("calendarView.viewMonth"),
+ week: t("calendarView.viewWeek"),
+ list: t("calendarView.viewList"),
+ };
+
+ return (
+ <SegmentedControl<CalendarViewMode>
+ label={t("calendarView.viewMode")}
+ value={value}
+ onChange={onChange}
+ // Icon track: 36px per segment plus the 6px track padding
+ className={
+ variant === "icon"
+ ? AVAILABLE_VIEW_MODES.length === 3
+ ? "w-[114px] shrink-0"
+ : "w-[78px] shrink-0"
+ : "shrink-0"
+ }
+ options={AVAILABLE_VIEW_MODES.map((mode) => {
+ const Icon = ICONS[mode];
+ return variant === "icon"
+ ? { value: mode, label: <Icon className="size-4" />, ariaLabel: labels[mode] }
+ : { value: mode, label: <span className="px-3">{labels[mode]}</span> };
+ })}
+ />
+ );
+}
+```
+
+- [ ] **Step 6: `components/app-header.tsx` — `step` on both steppers, switcher in the desktop row**
+
+Imports: replace the date-fns import with `import { addMonths, addWeeks, getISOWeek } from "date-fns";` (drop `format`, `subMonths`; drop the `getDateLocale` import if nothing else in the file uses it — `AppHeader` does not), add `import { formatPeriodCaption, PeriodStep } from "@/lib/date-utils";`, `import { ViewModeSwitcher } from "@/components/view-mode-switcher";`, `import { CalendarViewMode } from "@/hooks/useCalendarViewMode";`.
+
+Add one module-level helper above `MonthArrows`:
+
+```ts
+function stepDate(date: Date, step: PeriodStep, direction: 1 | -1): Date {
+ return step === "week" ? addWeeks(date, direction) : addMonths(date, direction);
+}
+```
+
+`MonthArrows`: add `step = "month"` to the props (`step?: PeriodStep`), and replace the two handlers/labels:
+
+```tsx
+ onClick={() => onDateChange(stepDate(currentDate, step, -1))}
+ aria-label={t(step === "week" ? "calendarView.previousWeek" : "calendarView.previousMonth")}
+```
+
+```tsx
+ onClick={() => onDateChange(stepDate(currentDate, step, 1))}
+ aria-label={t(step === "week" ? "calendarView.nextWeek" : "calendarView.nextMonth")}
+```
+
+`MonthStepper`: same `step` prop and the same two handler/label replacements; replace the caption span with:
+
+```tsx
+ <span
+ className={cn(
+ "text-center text-[15px] font-semibold text-fg-strong",
+ step === "week" ? "min-w-[232px]" : "min-w-[150px]"
+ )}
+ >
+ {formatPeriodCaption(currentDate, step, locale)}
+ {step === "week" && (
+ <span className="ml-2 font-mono text-[12px] font-medium text-fg-tertiary">
+ {t("calendarView.calendarWeek", { week: getISOWeek(currentDate) })}
+ </span>
+ )}
+ </span>
+```
+
+`AppHeaderProps`: add
+
+```ts
+ /** Absent in contexts without view modes; the switcher is then not rendered */
+ viewMode?: CalendarViewMode;
+ onViewModeChange?: (mode: CalendarViewMode) => void;
+```
+
+Destructure both in `AppHeader`. In the desktop row replace the `<MonthStepper …/>` line with:
+
+```tsx
+ <MonthStepper
+ currentDate={currentDate}
+ onDateChange={onDateChange}
+ step={viewMode === "week" ? "week" : "month"}
+ />
+ {viewMode && onViewModeChange && (
+ <ViewModeSwitcher value={viewMode} onChange={onViewModeChange} variant="text" />
+ )}
+```
+
+Note: the i18n checker greps literal keys. `t(step === "week" ? "calendarView.previousWeek" : "calendarView.previousMonth")` contains both literals, which is what it needs — verify with `npm run i18n` in Step 10; if it reports the keys as unused, split into two `t()` calls selected by a ternary on the results.
+
+- [ ] **Step 7: `components/calendar-workspace.tsx` — props and the mobile title row**
+
+Imports: add `import { ViewModeSwitcher } from "@/components/view-mode-switcher";`, `import { CalendarViewMode } from "@/hooks/useCalendarViewMode";`, `import { formatPeriodCaption } from "@/lib/date-utils";`. Remove `format` from the date-fns import and the `getDateLocale` import plus the `const dateLocale = …` line if nothing else uses them after this step.
+
+Props interface and destructuring: add `viewMode: CalendarViewMode;` and `onViewModeChange: (mode: CalendarViewMode) => void;`.
+
+Below the `stampingEnabled` line add `const step = viewMode === "week" ? "week" : "month";`.
+
+Replace the mobile title row (`<div className="flex items-center justify-between gap-2 px-3.5 pb-[9px] pt-3">…</div>`) with:
+
+```tsx
+ <div className="flex items-center gap-2 px-3.5 pb-[9px] pt-3">
+ <h1 className="min-w-0 flex-1 truncate text-[19px] font-semibold tracking-[-0.015em] text-fg-strong">
+ {formatPeriodCaption(currentDate, step, locale, { compact: true })}
+ </h1>
+ <ViewModeSwitcher value={viewMode} onChange={onViewModeChange} variant="icon" />
+ {isOnline ? (
+ <MonthArrows currentDate={currentDate} onDateChange={onDateChange} step={step} />
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-9 gap-2 font-semibold"
+ onClick={() => queryClient.refetchQueries()}
+ >
+ <RefreshCw className="size-4" />
+ {t("calendarView.retry")}
+ </Button>
+ )}
+ </div>
+```
+
+- [ ] **Step 8: `app/page.tsx` — own the mode, make the date handlers mode-aware**
+
+Imports: change the date-fns import to `import { addDays, isSameMonth, isSameWeek, startOfWeek } from "date-fns";`, change the calendar-utils import to `import { getCalendarDays, getMonthDays, getWeekDays } from "@/lib/calendar-utils";`, add `import { CalendarViewMode, useCalendarViewMode } from "@/hooks/useCalendarViewMode";`.
+
+Directly after the `useCompareMode({...})` call:
+
+```ts
+ const [storedViewMode, setViewMode] = useCalendarViewMode();
+ // Compare mode shares one month grid, whatever this device last used
+ const viewMode: CalendarViewMode = isCompareMode ? "month" : storedViewMode;
+```
+
+Replace `handleDateChange` with:
+
+```ts
+ // Navigation keeps the selection inside the visible period
+ const handleDateChange = (date: Date) => {
+ setCurrentDate(date);
+ if (viewMode === "week") {
+ if (!isSameWeek(selectedDay, date, { weekStartsOn: 1 })) {
+ const now = new Date();
+ selectDay(
+ isSameWeek(now, date, { weekStartsOn: 1 })
+ ? now
+ : addDays(startOfWeek(date, { weekStartsOn: 1 }), (selectedDay.getDay() + 6) % 7)
+ );
+ }
+ return;
+ }
+ if (!isSameMonth(selectedDay, date)) {
+ selectDay(isSameMonth(new Date(), date) ? new Date() : new Date(date.getFullYear(), date.getMonth(), 1));
+ }
+ };
+
+ // Switching the mode never moves the visible month; week anchors on the focused day
+ const handleViewModeChange = (mode: CalendarViewMode) => {
+ if (mode === "week" && isSameMonth(selectedDay, currentDate)) setCurrentDate(selectedDay);
+ setViewMode(mode);
+ };
+```
+
+Replace the `calendarDays` memo:
+
+```ts
+ const calendarDays = useMemo(
+ () =>
+ viewMode === "week"
+ ? getWeekDays(currentDate)
+ : viewMode === "list"
+ ? getMonthDays(currentDate)
+ : getCalendarDays(currentDate),
+ [currentDate, viewMode]
+ );
+```
+
+Pass `viewMode={viewMode}` and `onViewModeChange={handleViewModeChange}` to both `<AppHeader>` and `<CalendarWorkspace>`.
+
+- [ ] **Step 9: i18n keys**
+
+In `messages/de.json` under `calendarView`, right after `"nextMonth"`:
+
+```json
+ "previousWeek": "Vorherige Woche",
+ "nextWeek": "Nächste Woche",
+ "viewMode": "Ansicht",
+ "viewMonth": "Monat",
+ "viewWeek": "Woche",
+ "viewList": "Liste",
+```
+
+Mirror at the same position:
+
+| key | en | es | fr | it | cs |
+|---|---|---|---|---|---|
+| previousWeek | Previous week | Semana anterior | Semaine précédente | Settimana precedente | Předchozí týden |
+| nextWeek | Next week | Semana siguiente | Semaine suivante | Settimana successiva | Další týden |
+| viewMode | View | Vista | Vue | Vista | Zobrazení |
+| viewMonth | Month | Mes | Mois | Mese | Měsíc |
+| viewWeek | Week | Semana | Semaine | Settimana | Týden |
+| viewList | List | Lista | Liste | Elenco | Seznam |
+
+- [ ] **Step 10: Gate**
+
+Run: `npx tsc --noEmit && npm run lint && npm run i18n`
+Expected: all three exit 0. The switcher is not visible yet (`AVAILABLE_VIEW_MODES` has one entry) and the app behaves exactly as before.
+
+- [ ] **Step 11: Commit**
+
+```bash
+git add -A
+git commit -m "feat(ui): add month/week/list view mode state and switcher (#186)"
+```
+
+---
+
+### Task 2: Extract the shared day-cell renderers from `MonthGrid`
+
+Pure refactor: the month view must look and behave exactly as before.
+
+**Files:**
+- Create: `components/day-cell-entries.tsx`
+- Modify: `components/month-grid.tsx`
+
+**Interfaces:**
+- Produces (all from `@/components/day-cell-entries`):
+ - `TODAY_BADGE: string`
+ - `interface DayContent { layout: DayShiftLayout; events: CalendarNote[]; notes: CalendarNote[] }`
+ - `buildDayContents(days: Date[], shifts: ShiftWithCalendar[], notes: CalendarNote[], externalSyncs: ExternalSync[], layout: DayLayoutOptions, includeDay: (day: Date) => boolean): Map<string, DayContent>` — keyed by `formatDateToLocal(day)`
+ - `useSignupsEnabled(): (calendarId: string) => boolean`
+ - `useDayPress(onDayClick: (day: Date) => void, onDayContextMenu?: (day: Date) => void): (day: Date) => DayPressHandlers` where `DayPressHandlers = { onClick; onContextMenu; onTouchStart; onTouchEnd; onTouchMove }`
+ - `<SignupBadge shift enabled />`, `<ShiftChip shift showNote signupsEnabled wrap? />`, `<ExternalShiftChip shift wrap? />`, `<EventChip note wrap? />`, `<NoteLine note wrap? />`, `<MinimalSyncCounter sync count />`
+
+- [ ] **Step 1: Create `components/day-cell-entries.tsx`**
+
+```tsx
+"use client";
+
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslations } from "next-intl";
+import { CalendarClock, RefreshCw, StickyNote } from "lucide-react";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
+import { formatDateToLocal } from "@/lib/date-utils";
+import { findNotesForDate } from "@/lib/event-utils";
+import {
+ DayLayoutOptions,
+ DayShiftLayout,
+ buildDayShiftLayout,
+ formatSignupCapacityLabel,
+ formatTimeRange,
+ shiftVars,
+} from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+import { useCalendars } from "@/hooks/useCalendars";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+
+const LONG_PRESS_MS = 500;
+
+// The filled day number of "today", shared by every grid and the list
+export const TODAY_BADGE = "bg-brand font-semibold text-white dark:bg-brand-dot dark:text-[#0a1020]";
+
+export interface DayContent {
+ layout: DayShiftLayout;
+ events: CalendarNote[];
+ notes: CalendarNote[];
+}
+
+/** One pass over the shifts instead of scanning every shift and note per day. */
+export function buildDayContents(
+ days: Date[],
+ shifts: ShiftWithCalendar[],
+ notes: CalendarNote[],
+ externalSyncs: ExternalSync[],
+ layout: DayLayoutOptions,
+ includeDay: (day: Date) => boolean
+): Map<string, DayContent> {
+ const shiftsByDay = new Map<string, ShiftWithCalendar[]>();
+ for (const shift of shifts) {
+ if (!shift.date) continue;
+ const key = formatDateToLocal(shift.date as Date);
+ const list = shiftsByDay.get(key);
+ if (list) list.push(shift);
+ else shiftsByDay.set(key, [shift]);
+ }
+
+ const contents = new Map<string, DayContent>();
+ for (const day of days) {
+ const key = formatDateToLocal(day);
+ const included = includeDay(day);
+ const dayNotes = included ? findNotesForDate(notes, day) : [];
+ contents.set(key, {
+ layout: buildDayShiftLayout(included ? (shiftsByDay.get(key) ?? []) : [], externalSyncs, layout),
+ events: dayNotes.filter((n) => n.type === "event"),
+ notes: dayNotes.filter((n) => n.type !== "event"),
+ });
+ }
+ return contents;
+}
+
+/** Whether signups are on for a calendar; unknown calendars count as enabled. */
+export function useSignupsEnabled(): (calendarId: string) => boolean {
+ const { calendars } = useCalendars();
+ const { isAuthEnabled } = useAuthFeatures();
+ const byId = useMemo(
+ () => new Map(calendars.map((c) => [c.id, isAuthEnabled && (c.signupsEnabled ?? true)])),
+ [calendars, isAuthEnabled]
+ );
+ return (calendarId) => byId.get(calendarId) ?? true;
+}
+
+export interface DayPressHandlers {
+ onClick: () => void;
+ onContextMenu: (e: React.MouseEvent) => void;
+ onTouchStart: () => void;
+ onTouchEnd: () => void;
+ onTouchMove: () => void;
+}
+
+/** Click, right-click and 500ms long-press for a day; the long press swallows the click that follows it. */
+export function useDayPress(
+ onDayClick: (day: Date) => void,
+ onDayContextMenu?: (day: Date) => void
+): (day: Date) => DayPressHandlers {
+ const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const longPressed = useRef(false);
+
+ useEffect(
+ () => () => {
+ if (pressTimer.current) clearTimeout(pressTimer.current);
+ },
+ []
+ );
+
+ const cancelPress = () => {
+ if (pressTimer.current) clearTimeout(pressTimer.current);
+ pressTimer.current = null;
+ };
+
+ return (day) => ({
+ onClick: () => {
+ if (longPressed.current) {
+ longPressed.current = false;
+ return;
+ }
+ onDayClick(day);
+ },
+ onContextMenu: (e) => {
+ e.preventDefault();
+ onDayContextMenu?.(day);
+ },
+ onTouchStart: () => {
+ longPressed.current = false;
+ if (!onDayContextMenu) return;
+ pressTimer.current = setTimeout(() => {
+ longPressed.current = true;
+ onDayContextMenu(day);
+ }, LONG_PRESS_MS);
+ },
+ onTouchEnd: cancelPress,
+ onTouchMove: cancelPress,
+ });
+}
+
+/** Compact "N" / "N/capacity" badge. */
+export function SignupBadge({ shift, enabled }: { shift: ShiftWithCalendar; enabled: boolean }) {
+ const t = useTranslations();
+ if (!enabled) return null;
+ const count = shift.signups?.length ?? 0;
+ const capacity = shift.signupCapacity ?? null;
+ if (count === 0 && capacity == null) return null;
+ const label = capacity != null ? formatSignupCapacityLabel(t, count, capacity) : null;
+ return (
+ <span
+ className={cn(
+ "shrink-0 rounded-[4px] px-1 font-mono text-[10px] leading-4",
+ label?.isFull ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken/70 text-fg-tertiary"
+ )}
+ title={label?.text}
+ >
+ {capacity != null ? `${count}/${capacity}` : count}
+ </span>
+ );
+}
+
+const CHIP =
+ "shift-chip flex min-w-0 shrink-0 gap-1.5 rounded-[6px] py-0.5 pr-[7px] dark:[--shift-tint:14%]";
+// Month cells cut titles to one line; week and list let them wrap
+const lineClass = (wrap: boolean) => (wrap ? "block break-words" : "block truncate");
+
+function ChipTime({ shift, full }: { shift: ShiftWithCalendar; full: boolean }) {
+ const t = useTranslations();
+ return (
+ <span className="shrink-0 whitespace-nowrap font-mono text-[10.5px] leading-4 opacity-75">
+ {shift.isAllDay
+ ? t("calendarView.allDayShort")
+ : full || shift.segments?.length
+ ? formatTimeRange(shift)
+ : shift.startTime.slice(0, 5)}
+ </span>
+ );
+}
+
+export function ShiftChip({
+ shift,
+ showNote,
+ signupsEnabled,
+ wrap = false,
+}: {
+ shift: ShiftWithCalendar;
+ showNote: boolean;
+ signupsEnabled: boolean;
+ wrap?: boolean;
+}) {
+ return (
+ <span
+ className={cn(CHIP, "pl-[5px]")}
+ style={shiftVars(shift.color)}
+ title={`${shift.title}${shift.notes ? `\n${shift.notes}` : ""}`}
+ >
+ <span className="shift-rail w-[3px] shrink-0 self-stretch rounded-full" />
+ <span className="min-w-0 flex-1">
+ <span className={cn(lineClass(wrap), "text-[11.5px] font-medium leading-4")}>
+ {shift.title}
+ </span>
+ {showNote && shift.notes && (
+ <span className={cn(lineClass(wrap), "text-[10.5px] leading-[14px] opacity-75")}>
+ {shift.notes}
+ </span>
+ )}
+ </span>
+ <SignupBadge shift={shift} enabled={signupsEnabled} />
+ <ChipTime shift={shift} full={wrap} />
+ </span>
+ );
+}
+
+/** The sync icon takes the rail's place so imported entries stay recognisable. */
+export function ExternalShiftChip({
+ shift,
+ wrap = false,
+}: {
+ shift: ShiftWithCalendar;
+ wrap?: boolean;
+}) {
+ return (
+ <span
+ className={cn(CHIP, "pl-[5px]", wrap ? "items-start" : "items-center")}
+ style={shiftVars(shift.color)}
+ title={shift.title}
+ >
+ <RefreshCw className={cn("size-3 shrink-0", wrap && "mt-0.5")} />
+ <span className={cn("min-w-0 flex-1 text-[11.5px] font-medium leading-4", lineClass(wrap))}>
+ {shift.title}
+ </span>
+ <ChipTime shift={shift} full={wrap} />
+ </span>
+ );
+}
+
+export function EventChip({ note, wrap = false }: { note: CalendarNote; wrap?: boolean }) {
+ return (
+ <span
+ className={cn(
+ "flex min-w-0 shrink-0 gap-1.5 rounded-[6px] bg-cell-event px-[7px] shadow-[inset_0_0_0_1px_var(--cell-event-line)]",
+ wrap ? "items-start py-0.5" : "h-5 items-center"
+ )}
+ title={note.note}
+ >
+ <CalendarClock
+ className={cn("shift-icon size-3 shrink-0", wrap && "mt-0.5")}
+ style={shiftVars(note.color || undefined)}
+ />
+ <span
+ className={cn(
+ "min-w-0 flex-1 text-[11.5px] font-medium text-cell-event-ink",
+ wrap ? "break-words leading-4" : "truncate"
+ )}
+ >
+ {note.note}
+ </span>
+ </span>
+ );
+}
+
+export function NoteLine({ note, wrap = false }: { note: CalendarNote; wrap?: boolean }) {
+ return (
+ <span
+ className={cn("flex min-w-0 shrink-0 gap-1.5 px-1", wrap ? "items-start py-px" : "h-[18px] items-center")}
+ title={note.note}
+ >
+ <StickyNote className={cn("size-3 shrink-0 text-cell-note", wrap && "mt-0.5")} />
+ <span
+ className={cn(
+ "min-w-0 flex-1 text-[11.5px] text-fg-body dark:text-fg-secondary",
+ wrap ? "break-words leading-4" : "truncate"
+ )}
+ >
+ {note.note}
+ </span>
+ </span>
+ );
+}
+
+/** Count-only pill for an external sync in "minimal" display mode. */
+export function MinimalSyncCounter({ sync, count }: { sync: ExternalSync; count: number }) {
+ return (
+ <span
+ className="shift-chip flex shrink-0 items-center gap-1 rounded-[6px] px-[5px] py-0.5 dark:[--shift-tint:14%]"
+ style={shiftVars(sync.color)}
+ title={sync.name}
+ >
+ <RefreshCw className="size-3 shrink-0" />
+ <span className="font-mono text-[11px] font-semibold leading-4">{count}</span>
+ </span>
+ );
+}
+```
+
+The non-wrap class strings are copied from `month-grid.tsx` — compare them against the current file while extracting and keep the file's strings if they differ from the ones above.
+
+- [ ] **Step 2: Rewire `components/month-grid.tsx`**
+
+- Delete from the file: `LONG_PRESS_MS`, `TODAY_BADGE`, the `DayContent` interface, `signupsEnabledById`, `signupBadge`, `pressTimer`, `longPressed`, the cleanup `useEffect`, `cancelPress`, and the `useCalendars` / `useAuthFeatures` / `findNotesForDate` / `buildDayShiftLayout` / `formatTimeRange` / `CalendarClock` / `StickyNote` imports that become unused (the phone marks and the compare cell still use `CalendarClock`, `StickyNote`, `RefreshCw` — keep whatever is still referenced).
+- Import from the new module: `DayContent, EventChip, ExternalShiftChip, MinimalSyncCounter, NoteLine, ShiftChip, SignupBadge, TODAY_BADGE, buildDayContents, useDayPress, useSignupsEnabled`.
+- Add near the top of the component:
+
+```ts
+ const signupsEnabled = useSignupsEnabled();
+ const dayPress = useDayPress(onDayClick, onDayContextMenu);
+```
+
+- Replace the `dayContents` memo body:
+
+```ts
+ const dayContents = useMemo(() => {
+ const month = currentDate.getMonth();
+ return buildDayContents(
+ calendarDays,
+ shifts,
+ notes,
+ externalSyncs,
+ { maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort },
+ // Leading and trailing days of other months stay empty
+ (day) => day.getMonth() === month
+ );
+ }, [calendarDays, currentDate, shifts, notes, externalSyncs, maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort]);
+```
+
+- In `renderDesktopHead` replace the inline minimal-group span with `<MinimalSyncCounter key={sync.id} sync={sync} count={synced.length} />`.
+- In `renderDesktop` delete the local `chip` and `time` helpers and replace the `switch` body with:
+
+```tsx
+ switch (entry.kind) {
+ case "shift":
+ return (
+ <ShiftChip
+ key={entry.key}
+ shift={entry.shift}
+ showNote={showShiftNotes}
+ signupsEnabled={signupsEnabled(entry.shift.calendarId)}
+ />
+ );
+ case "external":
+ return <ExternalShiftChip key={entry.key} shift={entry.shift} />;
+ case "event":
+ return <EventChip key={entry.key} note={entry.note} />;
+ case "note":
+ return <NoteLine key={entry.key} note={entry.note} />;
+ }
+```
+
+- In `renderCompare` replace `{signupBadge(shift)}` with `<SignupBadge shift={shift} enabled={signupsEnabled(shift.calendarId)} />`.
+- On the day `<button>` replace the five inline handlers (`onClick`, `onContextMenu`, `onTouchStart`, `onTouchEnd`, `onTouchMove`) with `{...dayPress(day)}`.
+
+- [ ] **Step 3: Gate**
+
+Run: `npx tsc --noEmit && npm run lint && npm run i18n`
+Expected: exit 0, no unused-import warnings in `month-grid.tsx`.
+
+- [ ] **Step 4: Visual regression check**
+
+Start `npm run dev`, open the app at 1440×900 and at 390×844 with a calendar that has shifts, a note and an event. Month cells, chips, signup badges, the today badge, stamping a preset on a day, right-click → notes dialog must be unchanged compared to `main`.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add -A
+git commit -m "refactor(ui): share the day-cell renderers between calendar views"
+```
+
+---
+
+### Task 3: Week view (#184)
+
+**Files:**
+- Create: `components/week-grid.tsx`
+- Modify: `hooks/useCalendarViewMode.ts`, `components/calendar-workspace.tsx`
+
+**Interfaces:**
+- Consumes: everything Task 2 produces; `getWeekDays` days arrive as `calendarDays` from the page (Task 1).
+- Produces: `<WeekGrid variant days selectedDay shifts notes externalSyncs togglingDates layout showShiftNotes? highlightedWeekdays? highlightColor? onDayClick onDayContextMenu? />`
+
+- [ ] **Step 1: Create `components/week-grid.tsx`**
+
+```tsx
+"use client";
+
+import { useMemo } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { isSameDay, isToday } from "date-fns";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
+import { formatDateToLocal } from "@/lib/date-utils";
+import { DayLayoutOptions } from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+import {
+ DayContent,
+ EventChip,
+ ExternalShiftChip,
+ MinimalSyncCounter,
+ NoteLine,
+ ShiftChip,
+ TODAY_BADGE,
+ buildDayContents,
+ useDayPress,
+ useSignupsEnabled,
+} from "@/components/day-cell-entries";
+
+interface WeekGridProps {
+ variant: "desktop" | "phone";
+ /** Monday to Sunday */
+ days: Date[];
+ selectedDay: Date;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+ externalSyncs: ExternalSync[];
+ togglingDates: Set<string>;
+ layout: DayLayoutOptions;
+ showShiftNotes?: boolean;
+ highlightedWeekdays?: number[];
+ highlightColor?: string;
+ onDayClick: (date: Date) => void;
+ onDayContextMenu?: (date: Date) => void;
+}
+
+export function WeekGrid({
+ variant,
+ days,
+ selectedDay,
+ shifts,
+ notes,
+ externalSyncs,
+ togglingDates,
+ layout,
+ showShiftNotes = false,
+ highlightedWeekdays = [],
+ highlightColor,
+ onDayClick,
+ onDayContextMenu,
+}: WeekGridProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const signupsEnabled = useSignupsEnabled();
+ const dayPress = useDayPress(onDayClick, onDayContextMenu);
+ const desktop = variant === "desktop";
+
+ const { sortType, sortOrder, combinedSort } = layout;
+ // The per-day caps exist to fit month cells; a week day shows everything
+ const contents = useMemo(
+ () =>
+ buildDayContents(
+ days,
+ shifts,
+ notes,
+ externalSyncs,
+ { sortType, sortOrder, combinedSort },
+ () => true
+ ),
+ [days, shifts, notes, externalSyncs, sortType, sortOrder, combinedSort]
+ );
+
+ const formatters = useMemo(
+ () => ({
+ weekday: new Intl.DateTimeFormat(locale, { weekday: desktop ? "long" : "short" }),
+ month: new Intl.DateTimeFormat(locale, { month: "short" }),
+ }),
+ [locale, desktop]
+ );
+ const straddlesMonths = days.length > 0 && days[0].getMonth() !== days[days.length - 1].getMonth();
+
+ const renderEntries = (content: DayContent) => (
+ <>
+ {content.layout.visible.map((shift) =>
+ shift.syncedFromExternal ? (
+ <ExternalShiftChip key={shift.id} shift={shift} wrap />
+ ) : (
+ <ShiftChip
+ key={shift.id}
+ shift={shift}
+ showNote={showShiftNotes}
+ signupsEnabled={signupsEnabled(shift.calendarId)}
+ wrap
+ />
+ )
+ )}
+ {content.events.map((note) => (
+ <EventChip key={note.id} note={note} wrap />
+ ))}
+ {content.notes.map((note) => (
+ <NoteLine key={note.id} note={note} wrap />
+ ))}
+ </>
+ );
+
+ const isEmpty = (content: DayContent) =>
+ content.layout.visible.length === 0 &&
+ content.layout.minimalGroups.length === 0 &&
+ content.events.length === 0 &&
+ content.notes.length === 0;
+
+ return (
+ <div
+ className={cn(
+ desktop
+ ? "mx-[18px] mt-3.5 grid min-h-0 flex-1 grid-cols-7 gap-px border-y border-line bg-line-grid"
+ : "flex flex-col px-2"
+ )}
+ >
+ {days.map((day) => {
+ const key = formatDateToLocal(day);
+ const content = contents.get(key)!;
+ const today = isToday(day);
+ const selected = isSameDay(day, selectedDay);
+ const weekend = day.getDay() === 0 || day.getDay() === 6;
+ const highlighted = !!highlightColor && highlightedWeekdays.includes(day.getDay());
+ const toggling = togglingDates.has(key);
+
+ const counters = content.layout.minimalGroups.map(({ sync, shifts: synced }) => (
+ <MinimalSyncCounter key={sync.id} sync={sync} count={synced.length} />
+ ));
+
+ return (
+ <button
+ key={key}
+ type="button"
+ disabled={toggling}
+ aria-pressed={selected}
+ aria-label={day.toLocaleDateString()}
+ {...dayPress(day)}
+ style={highlighted ? ({ "--highlight": highlightColor } as React.CSSProperties) : undefined}
+ className={cn(
+ "relative min-w-0 select-none text-left outline-none transition-colors [-webkit-touch-callout:none]",
+ "focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]",
+ desktop
+ ? cn(
+ "flex min-h-0 flex-col items-stretch gap-[3px] overflow-y-auto px-2 pb-2",
+ weekend ? "bg-surface-weekend" : "bg-surface-cell",
+ "hover:bg-surface-panel",
+ selected && "shadow-[inset_0_0_0_1.5px_var(--brand-dot)]"
+ )
+ : cn(
+ "flex items-start gap-3 rounded-[10px] px-1.5 py-2.5",
+ selected && "bg-cell-selected"
+ ),
+ highlighted && "day-highlight",
+ toggling && "cursor-wait opacity-60"
+ )}
+ >
+ {desktop ? (
+ <>
+ {/* Sticky so the date stays readable while a full day scrolls */}
+ <span className="sticky top-0 z-10 -mx-2 flex shrink-0 items-center gap-1.5 bg-inherit px-2 pb-1.5 pt-2">
+ <span
+ className={cn(
+ "inline-flex h-[22px] min-w-[22px] shrink-0 items-center justify-center rounded-full px-1 font-mono text-[12.5px] font-medium leading-none",
+ today ? TODAY_BADGE : "text-fg-body dark:text-fg-secondary"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ <span className="min-w-0 truncate text-[11.5px] font-semibold uppercase tracking-[0.06em] text-fg-tertiary">
+ {formatters.weekday.format(day)}
+ {straddlesMonths && ` · ${formatters.month.format(day)}`}
+ </span>
+ {counters.length > 0 && (
+ <span className="ml-auto flex shrink-0 items-center gap-1">{counters}</span>
+ )}
+ </span>
+ {renderEntries(content)}
+ </>
+ ) : (
+ <>
+ <span className="flex w-10 shrink-0 flex-col items-center gap-0.5 pt-0.5">
+ <span className="text-[10.5px] font-semibold uppercase tracking-[0.06em] text-cell-muted">
+ {formatters.weekday.format(day)}
+ </span>
+ <span
+ className={cn(
+ "inline-flex size-[26px] items-center justify-center rounded-full font-mono text-[14px] leading-none",
+ today
+ ? TODAY_BADGE
+ : weekend
+ ? "font-[450] text-cell-weekend-num"
+ : "font-[450] text-fg-body"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-1 border-b border-line pb-2.5">
+ {counters.length > 0 && <span className="flex flex-wrap gap-1">{counters}</span>}
+ {renderEntries(content)}
+ {isEmpty(content) && (
+ <span className="py-1 text-[12.5px] text-fg-faint">{t("calendarView.dayFree")}</span>
+ )}
+ </span>
+ </>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+```
+
+`bg-inherit` on the sticky head only works if the button's background is set by a class on the button itself (it is). The `day-highlight` class sets its own background; check in the browser that the sticky head of a highlighted column does not show a mismatched strip — if it does, drop `bg-inherit` in favour of repeating the weekend/cell/highlight classes on the head.
+
+- [ ] **Step 2: `components/calendar-workspace.tsx` — pick the surface**
+
+Import `WeekGrid`. Replace `const grid = (<MonthGrid … />);` with:
+
+```tsx
+ const variant = desktop ? "desktop" : "phone";
+ const surface =
+ viewMode === "week" ? (
+ <WeekGrid
+ variant={variant}
+ days={calendarDays}
+ selectedDay={selectedDay}
+ shifts={visibleShifts}
+ notes={notes}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ layout={layout}
+ showShiftNotes={showShiftNotes}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ onDayClick={onDayClick}
+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
+ />
+ ) : (
+ <MonthGrid
+ variant={variant}
+ calendarDays={calendarDays}
+ currentDate={currentDate}
+ selectedDay={selectedDay}
+ shifts={visibleShifts}
+ notes={notes}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ layout={layout}
+ showShiftNotes={showShiftNotes}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ onDayClick={onDayClick}
+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
+ />
+ );
+```
+
+and replace both `{grid}` usages with `{surface}`. The desktop wrapper uses `[&>div]:opacity-60` while offline, which also matches `WeekGrid`'s root `div` — no change needed.
+
+- [ ] **Step 3: Enable the mode**
+
+In `hooks/useCalendarViewMode.ts`: `export const AVAILABLE_VIEW_MODES: readonly CalendarViewMode[] = ["month", "week"];`
+
+- [ ] **Step 4: Gate**
+
+Run: `npx tsc --noEmit && npm run lint && npm run i18n`
+Expected: exit 0.
+
+- [ ] **Step 5: Browser check (1440×900 and 390×844)**
+
+- The switcher now shows Month/Week; switching to Week keeps the month, shows the week of the selected day, caption reads like "14.–20. Sep. 2026 · KW 38".
+- Arrows step one week; step across a month boundary (caption collapses to two months) and across New Year.
+- A week straddling two months shows full content on all seven days.
+- Click selects (inspector / day sheet follows), armed preset stamps and un-stamps, right-click / long-press opens notes.
+- Month → Week → Month → Week returns to the same week. Reload restores Week.
+- Compare mode still shows the month grid and steps by month.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add -A
+git commit -m "feat(ui): add week view (#184)"
+```
+
+---
+
+### Task 4: List view (#185)
+
+**Files:**
+- Create: `components/shift-list-view.tsx`
+- Modify: `components/day-detail.tsx`, `components/mobile-day-sheet.tsx`, `components/calendar-workspace.tsx`, `app/page.tsx`, `hooks/useCalendarViewMode.ts`, `messages/*.json`
+
+**Interfaces:**
+- Consumes: `buildDayContents`, `useDayPress`, `EventChip`, `NoteLine`, `MinimalSyncCounter`, `TODAY_BADGE` (Task 2); `formatWeekRange` (Task 1); `getMonthDays` days arrive as `calendarDays`.
+- Produces:
+ - `ShiftDetailRow` prop `fullTitle?: boolean`
+ - `ListSort = { type: ShiftSortType; order: ShiftSortOrder; locked: boolean; onChange: (patch: { sortType?: ShiftSortType; sortOrder?: ShiftSortOrder }) => void }`
+ - `<ShiftListView …/>` (props below)
+ - `CalendarWorkspace` props `listSort: ListSort`, `onSelectDay: (day: Date) => void`
+ - `MobileDayFooter` prop `list?: { nextShift: ShiftWithCalendar | null; onJump: () => void }`
+
+- [ ] **Step 1: `components/day-detail.tsx` — `fullTitle` on `ShiftDetailRow`**
+
+Add `/** List view: title and note wrap instead of truncating */ fullTitle?: boolean;` to `ShiftDetailRowProps`, destructure `fullTitle = false`, and change the two lines:
+
+```tsx
+ <div className={cn("text-[13.5px] font-semibold text-fg-strong", fullTitle ? "break-words" : "truncate")}>
+ {shift.title}
+ </div>
+```
+
+```tsx
+ <div className={cn("mt-1 text-xs text-fg-secondary", fullTitle ? "whitespace-pre-line break-words" : "line-clamp-2")}>
+ {shift.notes}
+ </div>
+```
+
+- [ ] **Step 2: Create `components/shift-list-view.tsx`**
+
+```tsx
+"use client";
+
+import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { endOfWeek, getISOWeek, isSameDay, isSameWeek, isToday, startOfWeek } from "date-fns";
+import { ArrowDownUp, Lock, Plus, RefreshCw, Search, X } from "lucide-react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Button } from "@/components/ui/button";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
+import { formatDateToLocal, formatWeekRange } from "@/lib/date-utils";
+import {
+ ShiftSortOrder,
+ ShiftSortType,
+ formatHours,
+ getShiftMinutes,
+ shiftVars,
+} from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+import { ShiftDetailRow } from "@/components/day-detail";
+import {
+ EventChip,
+ MinimalSyncCounter,
+ NoteLine,
+ TODAY_BADGE,
+ buildDayContents,
+ useDayPress,
+} from "@/components/day-cell-entries";
+
+export interface ListSort {
+ type: ShiftSortType;
+ order: ShiftSortOrder;
+ /** The calendar pins its own view, so the personal sort would not apply */
+ locked: boolean;
+ onChange: (patch: { sortType?: ShiftSortType; sortOrder?: ShiftSortOrder }) => void;
+}
+
+interface ShiftListViewProps {
+ variant: "desktop" | "phone";
+ /** Every day of the visible month, so stamping by day click works on empty days too */
+ days: Date[];
+ selectedDay: Date;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+ presets: ShiftPreset[];
+ externalSyncs: ExternalSync[];
+ togglingDates: Set<string>;
+ sort: ListSort;
+ combinedSort: boolean;
+ highlightedWeekdays?: number[];
+ highlightColor?: string;
+ /** A preset is armed: clicking a shift row stamps the day instead of opening the shift */
+ stampArmed: boolean;
+ canAddShift: boolean;
+ onAddShift: () => void;
+ canEditShift: (shift: ShiftWithCalendar) => boolean;
+ canDeleteShift: (shift: ShiftWithCalendar) => boolean;
+ onEditShift: (shift: ShiftWithCalendar) => void;
+ onDeleteShift: (shift: ShiftWithCalendar) => void;
+ onDayClick: (date: Date) => void;
+ onDayContextMenu?: (date: Date) => void;
+ /** Bump `nonce` to scroll to `key` again */
+ scrollTarget?: { key: string; nonce: number } | null;
+}
+
+const NO_PRESET = "none";
+const WEEK = { weekStartsOn: 1 } as const;
+
+/** Filter chip a shift falls under: its sync, its preset, or "without preset". */
+function chipKeyOf(shift: ShiftWithCalendar, presetIds: Set<string>): string {
+ if (shift.syncedFromExternal && shift.externalSyncId) return `sync:${shift.externalSyncId}`;
+ return shift.presetId && presetIds.has(shift.presetId) ? `preset:${shift.presetId}` : NO_PRESET;
+}
+
+export function ShiftListView({
+ variant,
+ days,
+ selectedDay,
+ shifts,
+ notes,
+ presets,
+ externalSyncs,
+ togglingDates,
+ sort,
+ combinedSort,
+ highlightedWeekdays = [],
+ highlightColor,
+ stampArmed,
+ canAddShift,
+ onAddShift,
+ canEditShift,
+ canDeleteShift,
+ onEditShift,
+ onDeleteShift,
+ onDayClick,
+ onDayContextMenu,
+ scrollTarget,
+}: ShiftListViewProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const desktop = variant === "desktop";
+ const dayPress = useDayPress(onDayClick, onDayContextMenu);
+ const [query, setQuery] = useState("");
+ const [activeChips, setActiveChips] = useState<string[]>([]);
+ const scroller = useRef<HTMLDivElement>(null);
+ const rowRefs = useRef(new Map<string, HTMLDivElement>());
+
+ const weekdayFormat = useMemo(() => new Intl.DateTimeFormat(locale, { weekday: "short" }), [locale]);
+ const presetIds = useMemo(() => new Set(presets.map((p) => p.id)), [presets]);
+
+ // "minimal" syncs are listed in full here: the list is where details live
+ const listSyncs = useMemo(
+ () => externalSyncs.map((sync) => ({ ...sync, displayMode: "normal" as const })),
+ [externalSyncs]
+ );
+ const contents = useMemo(
+ () =>
+ buildDayContents(
+ days,
+ shifts,
+ notes,
+ listSyncs,
+ { sortType: sort.type, sortOrder: sort.order, combinedSort },
+ () => true
+ ),
+ [days, shifts, notes, listSyncs, sort.type, sort.order, combinedSort]
+ );
+
+ const chips = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const content of contents.values()) {
+ for (const shift of content.layout.visible) {
+ const key = chipKeyOf(shift, presetIds);
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+ const result: { key: string; label: string; color?: string; count: number; synced?: boolean }[] = [];
+ for (const preset of presets) {
+ const count = counts.get(`preset:${preset.id}`);
+ if (count) result.push({ key: `preset:${preset.id}`, label: preset.title, color: preset.color, count });
+ }
+ const none = counts.get(NO_PRESET);
+ if (none) result.push({ key: NO_PRESET, label: t("calendarView.listWithoutPreset"), count: none });
+ for (const sync of externalSyncs) {
+ const count = counts.get(`sync:${sync.id}`);
+ if (count) result.push({ key: `sync:${sync.id}`, label: sync.name, color: sync.color, count, synced: true });
+ }
+ return result;
+ }, [contents, presets, presetIds, externalSyncs, t]);
+
+ // A chip can vanish with its last shift or a month change; ignore stale selections
+ const chipKeys = new Set(chips.map((c) => c.key));
+ const effectiveChips = activeChips.filter((key) => chipKeys.has(key));
+ const needle = query.trim().toLocaleLowerCase(locale);
+ const filtering = needle.length > 0 || effectiveChips.length > 0;
+
+ const weeks = useMemo(() => {
+ const matches = (text: string | null | undefined) =>
+ !!text && text.toLocaleLowerCase(locale).includes(needle);
+ const groups: {
+ key: string;
+ start: Date;
+ days: { day: Date; key: string; shifts: ShiftWithCalendar[]; events: CalendarNote[]; notes: CalendarNote[] }[];
+ }[] = [];
+
+ for (const day of days) {
+ const key = formatDateToLocal(day);
+ const content = contents.get(key)!;
+ const dayShifts = content.layout.visible.filter(
+ (shift) =>
+ (effectiveChips.length === 0 || effectiveChips.includes(chipKeyOf(shift, presetIds))) &&
+ (!needle || matches(shift.title) || matches(shift.notes))
+ );
+ // Notes never match a preset filter; with a search they must match it
+ const showNotes = effectiveChips.length === 0;
+ const keepNote = (note: CalendarNote) => showNotes && (!needle || matches(note.note));
+ const events = content.events.filter(keepNote);
+ const dayNotes = content.notes.filter(keepNote);
+ if (filtering && dayShifts.length + events.length + dayNotes.length === 0) continue;
+
+ const start = startOfWeek(day, WEEK);
+ const weekKey = formatDateToLocal(start);
+ let group = groups[groups.length - 1];
+ if (!group || group.key !== weekKey) {
+ group = { key: weekKey, start, days: [] };
+ groups.push(group);
+ }
+ group.days.push({ day, key, shifts: dayShifts, events, notes: dayNotes });
+ }
+ return groups;
+ // effectiveChips is rebuilt per render; its joined value is the real dependency
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [days, contents, presetIds, needle, filtering, effectiveChips.join("|"), locale]);
+
+ const scrollToKey = (key: string) => {
+ const container = scroller.current;
+ const row = rowRefs.current.get(key);
+ if (!container) return;
+ // 32px keeps the row clear of the sticky week header
+ container.scrollTop = row ? Math.max(0, row.offsetTop - 32) : 0;
+ };
+
+ const monthKey = days.length > 0 ? formatDateToLocal(days[0]) : "";
+ const scrollToFocus = useEffectEvent(() => {
+ const todayKey = formatDateToLocal(new Date());
+ const selectedKey = formatDateToLocal(selectedDay);
+ const inMonth = (key: string) => days.some((d) => formatDateToLocal(d) === key);
+ scrollToKey(inMonth(todayKey) ? todayKey : inMonth(selectedKey) ? selectedKey : "");
+ });
+ useEffect(() => {
+ scrollToFocus();
+ }, [monthKey]);
+
+ const jumpTo = useEffectEvent((key: string) => scrollToKey(key));
+ useEffect(() => {
+ if (scrollTarget) jumpTo(scrollTarget.key);
+ }, [scrollTarget]);
+
+ const toggleChip = (key: string) =>
+ setActiveChips((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]));
+
+ const sortLabels: Record<ShiftSortType, string> = {
+ startTime: t("view.sortByStartTime"),
+ createdAt: t("view.sortByCreatedAt"),
+ title: t("view.sortByTitle"),
+ };
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className={cn("flex shrink-0 flex-col gap-2 border-b border-line", desktop ? "px-[18px] pb-2.5 pt-3.5" : "px-3.5 pb-2.5")}>
+ <div className="flex items-center gap-2">
+ <label className="relative min-w-0 flex-1">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-fg-tertiary" />
+ <input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t("calendarView.listSearchPlaceholder")}
+ aria-label={t("calendarView.listSearchPlaceholder")}
+ className="h-9 w-full rounded-lg border border-line bg-surface-card pl-8 pr-8 text-[13.5px] text-fg-strong outline-none placeholder:text-fg-faint focus-visible:border-brand-dot [&::-webkit-search-cancel-button]:hidden"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => setQuery("")}
+ aria-label={t("common.clear")}
+ className="absolute right-1.5 top-1/2 flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-sunken"
+ >
+ <X className="size-3.5" />
+ </button>
+ )}
+ </label>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={sort.locked}
+ title={sort.locked ? t("calendarView.listSortPinnedHint") : t("view.sortOptions")}
+ aria-label={t("view.sortOptions")}
+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-lg border border-line px-2.5 text-[13px] font-medium text-fg-secondary transition-colors hover:bg-surface-panel disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {sort.locked ? <Lock className="size-3.5" /> : <ArrowDownUp className="size-4" />}
+ {desktop && sortLabels[sort.type]}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>{t("view.sortBy")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sort.type}
+ onValueChange={(value) => sort.onChange({ sortType: value as ShiftSortType })}
+ >
+ {(Object.keys(sortLabels) as ShiftSortType[]).map((type) => (
+ <DropdownMenuRadioItem key={type} value={type}>
+ {sortLabels[type]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{t("view.sortOrder")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sort.order}
+ onValueChange={(value) => sort.onChange({ sortOrder: value as ShiftSortOrder })}
+ >
+ <DropdownMenuRadioItem value="asc">{t("view.sortOrderAsc")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="desc">{t("view.sortOrderDesc")}</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {desktop && canAddShift && (
+ <Button size="sm" onClick={onAddShift} className="h-9 shrink-0 gap-1.5 rounded-lg px-3 text-[13px] font-semibold">
+ <Plus className="size-[15px]" />
+ {t("calendarView.addShiftManually")}
+ </Button>
+ )}
+ </div>
+ {chips.length > 0 && (
+ <div className="-mx-1 flex gap-1.5 overflow-x-auto px-1 pb-0.5 [scrollbar-width:none]">
+ {chips.map((chip) => {
+ const active = effectiveChips.includes(chip.key);
+ return (
+ <button
+ key={chip.key}
+ type="button"
+ aria-pressed={active}
+ onClick={() => toggleChip(chip.key)}
+ className={cn(
+ "flex h-7 shrink-0 items-center gap-1.5 rounded-full border px-2.5 text-[12.5px] font-medium transition-colors",
+ active
+ ? "border-transparent bg-brand-soft text-brand-ink"
+ : "border-line text-fg-secondary hover:bg-surface-panel"
+ )}
+ >
+ {chip.synced ? (
+ <RefreshCw className="size-3 shrink-0" />
+ ) : chip.color ? (
+ <span className="shift-rail size-2 shrink-0 rounded-full" style={shiftVars(chip.color)} />
+ ) : null}
+ <span className="max-w-[180px] truncate">{chip.label}</span>
+ <span className="font-mono text-[11px] opacity-70">{chip.count}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ <div ref={scroller} className={cn("relative min-h-0 flex-1 overflow-y-auto", desktop ? "px-[18px]" : "px-2")}>
+ {weeks.length === 0 ? (
+ <p className="py-10 text-center text-[13px] text-fg-tertiary">
+ {filtering ? t("calendarView.listNoMatches") : t("shift.noShiftsInMonth")}
+ </p>
+ ) : (
+ weeks.map((week) => (
+ <section key={week.key}>
+ <h2 className="sticky top-0 z-10 flex items-baseline gap-2 bg-background py-1.5 pl-1 text-[11.5px] font-semibold uppercase tracking-[0.06em] text-fg-tertiary">
+ {isSameWeek(week.start, new Date(), WEEK) ? (
+ <span className="text-brand-ink">{t("calendarView.thisWeek")}</span>
+ ) : (
+ t("calendarView.calendarWeek", { week: getISOWeek(week.start) })
+ )}
+ <span className="font-mono font-normal normal-case tracking-normal text-fg-faint">
+ {formatWeekRange(week.start, endOfWeek(week.start, WEEK), locale, false)}
+ </span>
+ </h2>
+ {week.days.map(({ day, key, shifts: dayShifts, events, notes: dayNotes }) => {
+ const today = isToday(day);
+ const selected = isSameDay(day, selectedDay);
+ const weekend = day.getDay() === 0 || day.getDay() === 6;
+ const highlighted = !!highlightColor && highlightedWeekdays.includes(day.getDay());
+ const toggling = togglingDates.has(key);
+ const minutes = dayShifts.reduce((sum, s) => sum + getShiftMinutes(s), 0);
+ const empty = dayShifts.length + events.length + dayNotes.length === 0;
+ const press = dayPress(day);
+
+ return (
+ // Buttons must not nest: the gutter is the real control, the row forwards mouse clicks
+ <div
+ key={key}
+ ref={(el) => {
+ if (el) rowRefs.current.set(key, el);
+ else rowRefs.current.delete(key);
+ }}
+ onClick={toggling ? undefined : press.onClick}
+ onContextMenu={press.onContextMenu}
+ onTouchStart={press.onTouchStart}
+ onTouchEnd={press.onTouchEnd}
+ onTouchMove={press.onTouchMove}
+ style={highlighted ? ({ "--highlight": highlightColor } as React.CSSProperties) : undefined}
+ className={cn(
+ "flex cursor-pointer items-stretch gap-3 rounded-[10px] border-b border-line px-1.5 transition-colors [-webkit-touch-callout:none]",
+ empty ? "py-1.5" : "py-2.5",
+ selected ? "bg-cell-selected" : "hover:bg-surface-panel",
+ highlighted && "day-highlight",
+ toggling && "cursor-wait opacity-60"
+ )}
+ >
+ <button
+ type="button"
+ disabled={toggling}
+ aria-pressed={selected}
+ aria-label={day.toLocaleDateString()}
+ // The row's handler runs through bubbling; this only needs to be focusable
+ className="flex w-11 shrink-0 flex-col items-center gap-0.5 rounded-md pt-0.5 outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]"
+ >
+ <span className="text-[10.5px] font-semibold uppercase tracking-[0.06em] text-cell-muted">
+ {weekdayFormat.format(day)}
+ </span>
+ <span
+ className={cn(
+ "inline-flex size-[26px] items-center justify-center rounded-full font-mono text-[14px] leading-none",
+ today ? TODAY_BADGE : weekend ? "text-cell-weekend-num" : "text-fg-body"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ </button>
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ {empty ? (
+ <span className="flex h-full items-center text-[12.5px] text-fg-faint">
+ {t("calendarView.dayFree")}
+ </span>
+ ) : (
+ <>
+ {dayShifts.length > 0 && (
+ <span className="font-mono text-[11.5px] text-fg-tertiary">
+ {t("calendarView.shiftCount", { count: dayShifts.length })}
+ {minutes > 0 && ` · ${formatHours(minutes, locale)}`}
+ </span>
+ )}
+ {dayShifts.map((shift) => (
+ <ShiftDetailRow
+ key={shift.id}
+ shift={shift}
+ fullTitle
+ canEdit={canEditShift(shift)}
+ canDelete={canDeleteShift(shift)}
+ actions="menu"
+ // Armed presets win, as in the grids: the click bubbles to the row and stamps
+ onEdit={stampArmed ? () => undefined : onEditShift}
+ onDelete={onDeleteShift}
+ />
+ ))}
+ {events.map((note) => (
+ <EventChip key={note.id} note={note} wrap />
+ ))}
+ {dayNotes.map((note) => (
+ <NoteLine key={note.id} note={note} wrap />
+ ))}
+ </>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </section>
+ ))
+ )}
+ </div>
+ </div>
+ );
+}
+```
+
+Notes for the implementer:
+- `ShiftDetailRow`'s own `onClick` calls `onEdit` and does **not** stop propagation, so an un-armed click on a shift row both opens the shift sheet and selects the day. That is intended (the inspector follows). When `stampArmed`, `onEdit` is a no-op and the bubbled click stamps.
+- The `ShiftDetailRow` dropdown trigger and the quick-signup button already `stopPropagation()`. Radix renders menu items in a portal, but React synthetic events still bubble through the React tree — the existing `e.stopPropagation()` calls on the items cover that.
+- `MinimalSyncCounter` is imported for parity but unused because minimal syncs are expanded; remove the import if lint flags it.
+- `common.clear` — check `messages/de.json`; if the key does not exist use `common.close`'s sibling that fits, or add `calendarView.listClearSearch` ("Suche leeren") to the key table in Step 6.
+- If `DropdownMenuRadioGroup` / `DropdownMenuRadioItem` / `DropdownMenuLabel` are not exported by `components/ui/dropdown-menu.tsx`, use `DropdownMenuItem` with a `Check` icon on the active entry instead; do not edit the primitive.
+
+- [ ] **Step 3: `components/mobile-day-sheet.tsx` — footer list variant**
+
+Add to `MobileDayFooter`'s props: `list?: { nextShift: ShiftWithCalendar | null; onJump: () => void };` (import `ShiftWithCalendar` from `@/lib/types`, `formatTimeRange`, `shiftVars` from `@/lib/shift-display`, `formatLongDate` from `@/lib/date-utils`, `isToday`, `isTomorrow` from `date-fns`, `ChartColumn` from `lucide-react` — skip those already imported).
+
+Inside the component, before `return`:
+
+```tsx
+ const next = list?.nextShift ?? null;
+ const nextDay = next?.date
+ ? isToday(next.date)
+ ? t("calendarView.today")
+ : isTomorrow(next.date)
+ ? t("calendarView.tomorrow")
+ : formatLongDate(next.date, locale, { month: "short" })
+ : null;
+```
+
+Wrap the existing left side: render the block below when `list` is set, the existing `canViewStats ? … : …` otherwise.
+
+```tsx
+ {list ? (
+ <>
+ <button
+ type="button"
+ onClick={list.onJump}
+ disabled={!next}
+ className="flex min-w-0 flex-1 items-center gap-2.5 py-0.5 text-left"
+ >
+ {next && (
+ <span className="shift-rail h-[30px] w-1 shrink-0 rounded-full" style={shiftVars(next.color)} />
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[10.5px] leading-[14px] text-fg-tertiary">
+ {t("calendarView.nextShift")}
+ </span>
+ <span className="block truncate text-[13px] font-semibold leading-5 text-fg-strong">
+ {next
+ ? `${next.title} · ${nextDay}${next.isAllDay ? "" : ` · ${formatTimeRange(next)}`}`
+ : t("calendarView.noUpcomingShift")}
+ </span>
+ </span>
+ </button>
+ {canViewStats && (
+ <button
+ type="button"
+ onClick={onOpenStats}
+ aria-label={t("calendarView.openStats")}
+ className="flex size-10 shrink-0 items-center justify-center rounded-[11px] border border-line text-fg-secondary"
+ >
+ <ChartColumn className="size-[18px]" />
+ </button>
+ )}
+ </>
+ ) : canViewStats ? (
+ /* existing KPI button, unchanged */
+ ) : (
+ /* existing "all shifts in month" button, unchanged */
+ )}
+```
+
+- [ ] **Step 4: `components/calendar-workspace.tsx` — list surface, next shift, jump**
+
+Imports: `ShiftListView, ListSort` from `@/components/shift-list-view`; `formatDateToLocal` from `@/lib/date-utils`.
+
+Props: add `listSort: ListSort;` and `onSelectDay: (day: Date) => void;` (JSDoc: `/** Pure navigation: shows the day's month and selects it, never stamps */`).
+
+State and derived values (next to the other hooks):
+
+```ts
+ const [scrollTarget, setScrollTarget] = useState<{ key: string; nonce: number } | null>(null);
+
+ // Own shifts only: imported calendars (holidays, colleagues) are not "my next shift"
+ const nextShift = useMemo(() => {
+ if (viewMode !== "list") return null;
+ const now = new Date();
+ const todayKey = formatDateToLocal(now);
+ const nowTime = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
+ let best: { shift: ShiftWithCalendar; sortKey: string } | null = null;
+ for (const shift of visibleShifts) {
+ if (!shift.date || shift.syncedFromExternal) continue;
+ const dayKey = formatDateToLocal(shift.date as Date);
+ if (dayKey < todayKey) continue;
+ // Today's shifts that already ended are over; overnight ones (end < start) still count
+ const ended =
+ dayKey === todayKey &&
+ !shift.isAllDay &&
+ shift.endTime > shift.startTime &&
+ shift.endTime.slice(0, 5) <= nowTime;
+ if (ended) continue;
+ const sortKey = `${dayKey} ${shift.isAllDay ? "00:00" : shift.startTime}`;
+ if (!best || sortKey < best.sortKey) best = { shift, sortKey };
+ }
+ return best?.shift ?? null;
+ }, [viewMode, visibleShifts]);
+```
+
+Extend the `surface` expression with a first branch:
+
+```tsx
+ viewMode === "list" ? (
+ <ShiftListView
+ variant={variant}
+ days={calendarDays}
+ selectedDay={selectedDay}
+ shifts={visibleShifts}
+ notes={notes}
+ presets={presets}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ sort={listSort}
+ combinedSort={layout.combinedSort ?? false}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ stampArmed={selectedPresetIds.length > 0}
+ canAddShift={model.canAddShift}
+ onAddShift={actions.onAddShift}
+ canEditShift={model.canEditShift}
+ canDeleteShift={model.canDeleteShift}
+ onEditShift={actions.onEditShift}
+ onDeleteShift={actions.onDeleteShift}
+ onDayClick={onDayClick}
+ onDayContextMenu={canAddNote ? onDayContextMenu : undefined}
+ scrollTarget={scrollTarget}
+ />
+ ) : viewMode === "week" ? (
+```
+
+`surface` must now be declared **after** `model` (it reads `model.canAddShift`); move the block below the `model` constant.
+
+Mobile wrapper: change `<div className={`flex flex-1 flex-col pb-1${…}`}>` so it can host an inner scroller:
+
+```tsx
+ <div
+ className={cn(
+ "flex flex-1 flex-col pb-1",
+ viewMode === "list" && "min-h-0",
+ !isOnline && "opacity-60"
+ )}
+ >
+ {surface}
+ </div>
+```
+
+(import `cn` from `@/lib/utils`). On phones `<main>` is `overflow-y-auto`; in list mode the list's own scroller must take over, so give `<main>` `overflow-y-auto` only outside list mode: `className={cn("flex min-h-0 flex-1 flex-col", viewMode !== "list" && "overflow-y-auto")}`.
+
+Footer: pass
+
+```tsx
+ list={
+ viewMode === "list"
+ ? {
+ nextShift,
+ onJump: () => {
+ if (!nextShift?.date) return;
+ const day = nextShift.date as Date;
+ onSelectDay(day);
+ setScrollTarget((prev) => ({ key: formatDateToLocal(day), nonce: (prev?.nonce ?? 0) + 1 }));
+ },
+ }
+ : undefined
+ }
+```
+
+If the jump crosses into another month the list remounts its rows and its month effect scrolls to today/selection first; the `scrollTarget` effect runs in the same commit afterwards and wins. Verify this in Step 8.
+
+- [ ] **Step 5: `app/page.tsx` — sort binding and pure day selection**
+
+Add to the `<CalendarWorkspace>` props:
+
+```tsx
+ listSort={{
+ type: calendarView.sortType,
+ order: calendarView.sortOrder,
+ // A calendar-pinned view replaces the personal one, so the personal sort is moot
+ locked: !!calendars.find((c) => c.id === selectedCalendar)?.viewSettings,
+ onChange: viewSettings.updatePersonal,
+ }}
+ onSelectDay={(day) => {
+ setCurrentDate(day);
+ selectDay(day);
+ }}
+```
+
+If `CalendarWithCount` has no `viewSettings` field, check how `viewSettings.forCalendar(calendar)` reads it and use the same property.
+
+- [ ] **Step 6: i18n keys**
+
+`messages/de.json` under `calendarView` (after `"viewList"`):
+
+```json
+ "thisWeek": "Diese Woche",
+ "listSearchPlaceholder": "Schichten und Notizen durchsuchen",
+ "listNoMatches": "Keine Treffer für diese Suche oder diesen Filter.",
+ "listWithoutPreset": "Ohne Vorlage",
+ "listSortPinnedHint": "Dieser Kalender legt die Sortierung fest.",
+ "nextShift": "Nächste Schicht",
+ "noUpcomingShift": "Keine anstehende Schicht",
+```
+
+| key | en | es | fr | it | cs |
+|---|---|---|---|---|---|
+| thisWeek | This week | Esta semana | Cette semaine | Questa settimana | Tento týden |
+| listSearchPlaceholder | Search shifts and notes | Buscar turnos y notas | Rechercher des services et des notes | Cerca turni e note | Hledat směny a poznámky |
+| listNoMatches | Nothing matches this search or filter. | Nada coincide con esta búsqueda o filtro. | Aucun résultat pour cette recherche ou ce filtre. | Nessun risultato per questa ricerca o filtro. | Tomuto hledání nebo filtru nic neodpovídá. |
+| listWithoutPreset | No preset | Sin plantilla | Sans modèle | Senza modello | Bez šablony |
+| listSortPinnedHint | This calendar sets the sort order. | Este calendario define el orden. | Ce calendrier définit le tri. | Questo calendario definisce l'ordinamento. | Řazení určuje tento kalendář. |
+| nextShift | Next shift | Próximo turno | Prochain service | Prossimo turno | Další směna |
+| noUpcomingShift | No upcoming shift | Ningún turno próximo | Aucun service à venir | Nessun turno in programma | Žádná nadcházející směna |
+
+Before translating "shift"/"preset", grep each locale file for how `calendarView.shift` and `calendarView.stamp` are already translated and use the same word.
+
+- [ ] **Step 7: Enable the mode**
+
+`hooks/useCalendarViewMode.ts`: `AVAILABLE_VIEW_MODES = ["month", "week", "list"]`.
+
+- [ ] **Step 8: Gate + browser check**
+
+Run: `npx tsc --noEmit && npm run lint && npm run i18n` → exit 0.
+
+Browser (1440×900 and 390×844): every day of the month is a row under week headers; "Diese Woche" on the current week; opens scrolled to today. Long titles wrap in full. Search narrows to matching days, chips filter by preset with correct counts, both combine; clearing restores all days. Sort menu changes order within a day and persists; with a calendar-pinned view it is disabled with the hint. Day click selects (inspector/day sheet), armed preset stamps on empty and filled days (also when clicking on a shift row), right-click/long-press opens notes. Shift row click opens the shift sheet, menu edits/deletes; external shifts are read-only. Phone footer shows the next shift, tapping jumps to it (also across months); stats icon opens the stats sheet. `onlyMyShifts` filters the list.
+
+- [ ] **Step 9: Commit**
+
+```bash
+git add -A
+git commit -m "feat(ui): add list view with search, preset filter and sorting (#185)"
+```
+
+---
+
+### Task 5: Retire `MonthShiftsDialog`; its entry points open the list
+
+**Files:**
+- Modify: `components/day-inspector.tsx`, `components/mobile-day-sheet.tsx`, `components/calendar-workspace.tsx`, `components/month-dialogs.tsx`, `components/dialog-manager.tsx`, `hooks/useDialogStates.ts`, `app/page.tsx`, `messages/*.json` (only if keys become unused)
+
+**Interfaces:**
+- Produces: `DayActions.onShowList?: () => void` (replaces `onOpenMonthShifts`; `undefined` while already in list mode, which hides the entry points). `MobileDayFooter` prop `onShowList?: () => void` (replaces `onOpenMonthShifts`).
+
+- [ ] **Step 1: `components/day-inspector.tsx`**
+
+In `DayActions` replace `onOpenMonthShifts: () => void;` with:
+
+```ts
+ /** Switches to the list view; absent while it is already showing */
+ onShowList?: () => void;
+```
+
+In the bottom section: render the `List` button only when `actions.onShowList` exists (`onClick={actions.onShowList}`), and render the whole `<div className="border-t …">` section only when `canViewStats || actions.onShowList` — otherwise it would be a lone caption.
+
+- [ ] **Step 2: `components/mobile-day-sheet.tsx`**
+
+- `MobileDayFooter`: rename the prop `onOpenMonthShifts` → `onShowList?: () => void`. In the non-stats fallback branch render the "all shifts in month" button only when `onShowList` is set; otherwise render `<span className="flex-1" />` so the "+" stays right-aligned.
+- `MobileStatsSheet`: change `{period === "month" && (` to `{period === "month" && actions.onShowList && (` and `onClick={run(actions.onShowList)}`.
+
+- [ ] **Step 3: `components/calendar-workspace.tsx`**
+
+`onOpenMonthShifts={actions.onOpenMonthShifts}` → `onShowList={actions.onShowList}`.
+
+- [ ] **Step 4: `app/page.tsx`**
+
+In the `actions` object replace the `onOpenMonthShifts` line with:
+
+```ts
+ onShowList:
+ viewMode === "list"
+ ? undefined
+ : () => {
+ setDaySheetOpen(false);
+ handleViewModeChange("list");
+ },
+```
+
+Remove the `showMonthShiftsDialog` / `onMonthShiftsDialogChange` props from `<DialogManager>`.
+
+- [ ] **Step 5: Remove the dialog**
+
+- `components/month-dialogs.tsx`: delete `MonthShiftsDialog` and the imports only it used (`useMemo`, `useLocale`, `format`, `ShiftDetailRow`, `ShiftWithCalendar`, `getDateLocale`, `formatDateToLocal`, `formatLongDate`, `formatHours`, `getShiftMinutes`, `sortShifts` — keep what `MonthStatsDialog` needs).
+- `components/dialog-manager.tsx`: remove the `MonthShiftsDialog` import, its JSX block, and the `showMonthShiftsDialog` / `onMonthShiftsDialogChange` props. Then check each of `shifts`, `canEditShift`, `canDeleteShift`, `onDeleteShift`, `currentDate` in `DialogManagerProps`: if nothing else in the file reads a prop, remove it from the interface and from `app/page.tsx`'s `<DialogManager>` call.
+- `hooks/useDialogStates.ts`: remove `showMonthShiftsDialog` / `setShowMonthShiftsDialog`.
+
+- [ ] **Step 6: Gate**
+
+Run: `npx tsc --noEmit && npm run lint && npm run i18n`
+Expected: exit 0. If `npm run i18n` reports unused keys, delete them from all six locale files (`calendarView.allShiftsIn` and `shift.noShiftsInMonth` are still used and must stay).
+
+- [ ] **Step 7: Browser check**
+
+Desktop inspector list icon, phone footer fallback button (calendar without `viewStats`), and the button inside the stats sheet each switch to the list view and close any open sheet; in list mode none of the three is shown.
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add -A
+git commit -m "feat(ui): open the list view instead of the month shifts dialog"
+```
+
+---
+
+### Task 6: Final verification
+
+- [ ] **Step 1:** `npm run build` → succeeds (this is CI's type check).
+- [ ] **Step 2:** Run the spec's full verification list (`Verification` section) with Playwright at 1440×900 and 390×844, including: read-only / guest calendar in all three modes, offline dimming, `AUTH_ENABLED=false` if the dev environment uses it, dark mode spot check of week and list.
+- [ ] **Step 3:** `git status` clean except intended files; `git log --oneline origin/main..` shows the spec, the plan and the five commits above.
diff --git a/docs/superpowers/specs/2026-09-17-calendar-view-modes-design.md b/docs/superpowers/specs/2026-09-17-calendar-view-modes-design.md
new file mode 100644
index 0000000..ce407bb
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-17-calendar-view-modes-design.md
@@ -0,0 +1,163 @@
+# Calendar View Modes (Month / Week / List) — Design
+
+Source: GitHub issues [#184](https://github.com/panteLx/BetterShift/issues/184) (week view), [#185](https://github.com/panteLx/BetterShift/issues/185) (list view) and [#186](https://github.com/panteLx/BetterShift/issues/186) (switcher). The month grid is the only calendar surface today; week-by-week planners have to read a whole month, and shift titles truncate in the narrow month cells with no surface that shows them in full.
+
+## Goals
+
+- Three renderings of the same calendar data — month (today's grid), week, list — selectable through one control in the header.
+- Switching the mode never changes the period being looked at, only how it is rendered.
+- Every existing day interaction (select, stamp/toggle a preset, note context menu / long press, day inspector, mobile day sheet, read-only and guest states, `onlyMyShifts`) behaves identically in all three modes.
+- The list view shows full, un-truncated shift titles and replaces the read-only "all shifts in <month>" dialog.
+
+## Non-goals
+
+- No schema or fetching change. Shifts, notes, presets and external syncs are already loaded per calendar without a date scope; week and list filter the arrays that are in memory. The one API change: `GET /api/shifts` now returns `presetId`, which the list's preset filter chips need.
+- The mode is not an account-synced preference and cannot be pinned by a calendar (`calendars.viewSettings`). `lib/view-settings.ts` is untouched.
+- Compare mode stays a month view; the switcher is not shown there.
+- Week start stays hardcoded to Monday, as everywhere else in the app.
+- No time-axis ("agenda with hours") week layout; the week view is day columns with stacked entries.
+- No swipe gesture for paging.
+
+## Decisions taken with the maintainer
+
+| Question | Decision |
+|---|---|
+| Persisting the mode (open in #184/#186) | `localStorage`, per device. Survives reloads, not synced to the account. |
+| Week view architecture | New `WeekGrid` component; the cell entry renderers are extracted from `MonthGrid` and shared. |
+| Week view on phones | Seven full-width day rows stacked vertically, not seven ~54px columns. |
+| Old `MonthShiftsDialog` | Removed. Its three entry points switch to list mode instead. |
+| Delivery | One branch `feat/calendar-view-modes`, one `feat` commit per issue (#186 → #184 → #185). |
+
+## Mode state and navigation (#186)
+
+### `hooks/useCalendarViewMode.ts`
+
+```ts
+export type CalendarViewMode = "month" | "week" | "list";
+export function useCalendarViewMode(): [CalendarViewMode, (mode: CalendarViewMode) => void];
+```
+
+- Backed by `localStorage` key `calendar-view-mode` (kebab-case, matching the per-device keys in `hooks/useViewSettings.ts`). Unknown or missing values resolve to `"month"`.
+- Read through `useSyncExternalStore` with a server snapshot of `"month"`, so SSR and first client render agree and there is no hydration mismatch. Storage access is wrapped in try/catch like `readStorage` in `useViewSettings.ts`.
+- Owned by `app/page.tsx`. While compare mode is active the page ignores the stored mode and nothing of this feature renders.
+
+### Date anchor
+
+`currentDate` in `app/page.tsx` stays the single anchor:
+
+| Mode | Visible period | Days passed down | Step |
+|---|---|---|---|
+| month | month of `currentDate` | `getCalendarDays(currentDate)` | ±1 month |
+| week | Monday–Sunday week containing `currentDate` | `getWeekDays(currentDate)` | ±1 week |
+| list | month of `currentDate` | every day of that month (`getMonthDays(currentDate)`) | ±1 month |
+
+`getWeekDays` and `getMonthDays` are added to `lib/calendar-utils.ts` next to `getCalendarDays`.
+
+Mode changes go through one page handler:
+
+- → `week`: if `selectedDay` lies in the visible month, `currentDate` is set to `selectedDay`, so the week shown is the one the user was focused on. The visible month does not change by this. Otherwise `currentDate` is kept.
+- → `month` / `list`: `currentDate` is kept; the month of the week's anchor is shown. Going back to `week` lands on the same week because the anchor never moved.
+
+`handleDateChange` becomes mode-aware: in week mode, when `selectedDay` falls outside the new week it moves to today if today is in that week, else to the same weekday of the new week. Month and list keep today's behaviour (today or the 1st).
+
+`handleDayClick` is unchanged. Its `!isSameMonth(day, currentDate) → setCurrentDate(day)` branch is harmless in week mode: a day of a month-straddling week is still in the same week.
+
+### Stepper and caption
+
+`MonthStepper` and `MonthArrows` in `components/app-header.tsx` gain `step?: "month" | "week"` (default `"month"`, so `compare-workspace.tsx` needs no change):
+
+- `step="week"` uses `addWeeks`/`subWeeks`, aria labels `calendarView.previousWeek` / `calendarView.nextWeek`.
+- The caption comes from a new `formatPeriodCaption(date, step, locale)` helper in `lib/date-utils.ts`: month → `LLLL yyyy` as today; week → a locale-formatted range that collapses shared parts ("8.–14. Sep. 2026", "29. Sep. – 5. Okt. 2026", "29. Dez. 2025 – 4. Jan. 2026"), built with `Intl.DateTimeFormat(locale).formatRange`. The desktop stepper appends the ISO week as muted text using the existing `calendarView.calendarWeek` key. The stepper's label min-width grows in week mode so the arrows don't jump.
+- The mobile title in `calendar-workspace.tsx` uses the same helper.
+
+### Switcher
+
+`components/view-mode-switcher.tsx` wraps `components/segmented-control.tsx`:
+
+- **Desktop**: in `AppHeader`'s desktop row directly right of `MonthStepper` (before the flex spacer), text labels `calendarView.viewMonth|viewWeek|viewList`.
+- **Mobile**: in the title row of `CalendarWorkspace`, between the title and `MonthArrows`. Three text segments do not fit next to a week-range title at 360px, so the phone variant renders icons (`CalendarDays`, `CalendarRange`, `List`) with the labels as `aria-label`/`title`. `SegmentedControl`'s `label` is typed `string` and rendered as the button content; it is widened to `React.ReactNode` plus an optional per-option `ariaLabel`. This is a project component, not a generated shadcn primitive.
+- `AppHeader` gets `viewMode` / `onViewModeChange` props; when `onViewModeChange` is absent the switcher is not rendered.
+
+## Week view (#184)
+
+### Shared cell renderers — `components/day-cell-entries.tsx`
+
+Extracted from `MonthGrid` without behaviour change:
+
+- `ShiftChip`, `ExternalShiftChip`, `EventChip`, `NoteLine` — the four desktop entry renderers (today inline in `renderDesktop`), with a `truncate` flag so the week/list surfaces can let titles wrap.
+- `SignupBadge` and the `signupsEnabledById` lookup as a `useSignupsEnabled()` hook.
+- `MinimalSyncCounter` — the count-only external sync pill from `renderDesktopHead`.
+- `useDayPress(onClick, onContextMenu)` — the click / context-menu / 500 ms long-press handler bundle, returning the props to spread on a day button.
+- `buildDayContents(days, shifts, notes, externalSyncs, layout, includeDay)` — the one-pass bucketing from the `dayContents` memo. `MonthGrid` passes `includeDay = day is in the current month` (today's behaviour); week and list pass `() => true`.
+- `TODAY_BADGE` moves here.
+
+`MonthGrid` keeps its px fitting, its three variants and its markup; it only imports these pieces.
+
+### `components/week-grid.tsx`
+
+Props mirror `MonthGrid` minus `variant`/`currentDate`, plus `variant: "desktop" | "phone"`. Content is built without `maxShifts` / `maxExternalShifts` (`undefined` = uncapped in `buildDayShiftLayout`) — the per-day cap exists to fit month cells and does not apply here — while `sortType` / `sortOrder` / `combinedSort` are honoured.
+
+- **Desktop**: one row of seven columns filling the main area. Column header: long weekday name plus day number (today badge, muted month abbreviation when the week straddles two months). The column itself is the day button (`useDayPress`), scrolls vertically on overflow, and stacks all entries with wrapping titles, full time range (`formatTimeRange`), signup badge and — when `showShiftNotes` is on — the shift note in full. Weekend tint, weekday highlight, selection ring, `togglingDates` disabled state and focus ring match the month cell.
+- **Phone**: seven full-width rows. Left: short weekday + day number (today/selected styling as in the phone month cell). Right: entries as full-width fields with title and time, events and notes below. Rows grow with their content; the page scrolls. A highlighted weekday tints the row.
+- Days outside `currentDate`'s month are not dimmed and show full content.
+
+`CalendarWorkspace` picks `MonthGrid`, `WeekGrid` or the list by a new `viewMode` prop. `DayInspector`, `StampDock`, `MobilePresetBar`, `MobileDayFooter`, the sheets, banners and the offline dimming are shared by all modes. The month summary (inspector KPIs, mobile footer) stays anchored on `currentDate`'s month in every mode.
+
+## List view (#185)
+
+### `components/shift-list-view.tsx`
+
+Replaces the grid in list mode; the stamp bar and inspector stay where they are.
+
+**Rows.** One row per calendar day of the month — every day must be present so stamping by day click keeps working. The row is the day button (`useDayPress`: select, stamp, note context menu). Left: weekday + day number. Right: that day's shifts as `ShiftDetailRow` (`components/day-detail.tsx`, `actions="menu"`, per-shift `canEditShift`/`canDeleteShift`, read-only for `syncedFromExternal`), which already shows color rail, full title, time range and duration; then events and notes as compact one-line entries. Empty days render a slim row with the existing `calendarView.dayFree` text. Buttons must not nest, so the row is a `div`: the left date gutter is the actual `<button>` (`useDayPress`, `aria-pressed`, disabled while toggling) and stretches over the row's height; the row container additionally forwards plain mouse clicks and the context menu on its free area to the same handlers, while `ShiftDetailRow`'s menu stops propagation. A click on a shift row opens the shift and selects its day without bubbling to the day row, via a separate `onOpen` on `ShiftDetailRow`; with a preset armed, the click bubbles up and stamps the day instead.
+
+**Grouping.** Rows sit under sticky week headers: "Diese Woche" (`calendarView.thisWeek`) for the current week, otherwise `KW n · <range>` via `formatPeriodCaption`. Day header meta shows shift count and hours like the old dialog (`calendarView.shiftCount`, `formatHours`).
+
+**Toolbar** (sticky above the rows):
+
+- Search input — matches shift title and shift notes, event/note text; case-insensitive.
+- Preset filter chips with counts for the visible month, built from `shift.presetId` joined with `presets` (color + title); shifts without a preset fall under one "Ohne Vorlage" chip, externally synced shifts under one chip per sync. Multi-select; no chip active = all.
+- Sort control bound to the personal `sortType` / `sortOrder` through `updatePersonal` from `useViewSettings` — no new sort state. When the calendar pins its own view the control is disabled with a hint (`calendarView.listSortPinnedHint`), since the personal value would not apply. Days are always chronological; sorting applies within a day.
+- "Schicht manuell" button → `actions.onAddShift` for the selected day; hidden without `canAddShift`.
+
+While a search or filter is active, days without a match are hidden, and events/notes only show when they match the search (they never match a preset filter). An empty result shows `shift.noShiftsInMonth` or a "no matches" text.
+
+Search and filter are component state and reset on calendar switch.
+
+**Scroll position.** On mount and when the month changes, the list scrolls to today's row if it is in the month, else to `selectedDay`, else the top.
+
+**Mobile footer.** In list mode `MobileDayFooter`'s left side shows the next upcoming shift of the calendar (first shift today-or-later by date and start time, from `visibleShifts`): title, relative day (`today`/`tomorrow`/date) and time. Tapping it navigates to that shift's month, selects the day and scrolls to it. Without an upcoming shift it shows `calendarView.noUpcomingShift`. The "+" button stays; a compact stats icon button is added next to it when `canViewStats`, so list mode does not lose the stats entry the KPI strip provides in the other modes.
+
+### Removing `MonthShiftsDialog`
+
+- Delete `MonthShiftsDialog` from `components/month-dialogs.tsx` (`MonthStatsDialog` stays), its wiring in `components/dialog-manager.tsx`, `showMonthShiftsDialog` in `hooks/useDialogStates.ts` and the props in `app/page.tsx`.
+- `DayActions.onOpenMonthShifts` is renamed `onShowList` and sets the mode to `"list"` (closing the mobile day/stats sheet first). Its three entry points — `DayInspector`, `MobileDayFooter` fallback button, `MobileStatsSheet` — are hidden while already in list mode.
+- `ShiftsOverviewDialog` (single day) is untouched.
+
+## i18n
+
+New keys under `calendarView` in `messages/de.json` first, then mirrored to `en`, `es`, `fr`, `it`, `cs`: `viewMode`, `viewMonth`, `viewWeek`, `viewList`, `previousWeek`, `nextWeek`, `thisWeek`, `listSearchPlaceholder`, `listClearSearch`, `listNoMatches`, `listWithoutPreset`, `listSort`, `listSortPinnedHint`, `nextShift`, `noUpcomingShift`, `addShiftManually` (final names settle during implementation; reuse existing keys where one fits). Keys left unused by the dialog removal are deleted so `npm run i18n` stays green.
+
+## Files
+
+| New | Purpose |
+|---|---|
+| `hooks/useCalendarViewMode.ts` | persisted mode |
+| `components/view-mode-switcher.tsx` | segmented control, desktop + phone variant |
+| `components/day-cell-entries.tsx` | shared renderers, `useDayPress`, `buildDayContents` |
+| `components/week-grid.tsx` | week view |
+| `components/shift-list-view.tsx` | list view |
+
+Changed: `app/page.tsx`, `components/app-header.tsx`, `components/calendar-workspace.tsx`, `components/month-grid.tsx`, `components/segmented-control.tsx`, `components/day-inspector.tsx`, `components/mobile-day-sheet.tsx`, `components/month-dialogs.tsx`, `components/dialog-manager.tsx`, `hooks/useDialogStates.ts`, `lib/calendar-utils.ts`, `lib/date-utils.ts`, `messages/*.json`.
+
+## Commits
+
+1. `feat(ui): add month/week/list view mode state and switcher (#186)` — mode hook, switcher, week-aware stepper/caption, mode-aware date handlers.
+2. `refactor(ui): share the day-cell renderers between calendar views` — extracts `day-cell-entries.tsx` from `MonthGrid` ahead of the week view.
+3. `feat(ui): add week view (#184)` — `WeekGrid`, `"week"` enabled.
+4. `feat(ui): add list view with search, preset filter and sorting (#185)` — `ShiftListView`, footer change, `"list"` enabled.
+5. `feat(ui): open the list view instead of the month shifts dialog` — retires `MonthShiftsDialog`, rewires its three entry points to `onShowList`.
+
+## Verification
+
+No unit-test framework exists in this repo. Per commit: `npx tsc --noEmit`, `npm run lint`, `npm run i18n`; at the end `npm run build`. Manual/Playwright pass at 1440×900 and 390×844 covering: mode switching keeps the period; week stepping across a month and a year boundary; stamping and un-stamping in all three modes; note long-press / context menu; list search, preset filter, sort control (enabled, and disabled under a calendar-pinned view); removed-dialog entry points switch to list; read-only/guest calendar; reload restores the mode; compare mode unaffected; month view pixel-identical to before the extraction.
diff --git a/hooks/useCalendarViewMode.ts b/hooks/useCalendarViewMode.ts
new file mode 100644
index 0000000..e193f28
--- /dev/null
+++ b/hooks/useCalendarViewMode.ts
@@ -0,0 +1,48 @@
+"use client";
+
+import { useCallback, useSyncExternalStore } from "react";
+
+export type CalendarViewMode = "month" | "week" | "list";
+
+/** Modes that have a surface; the switcher offers exactly these. */
+export const AVAILABLE_VIEW_MODES: readonly CalendarViewMode[] = ["month", "week", "list"];
+
+// Per-device like the view-setting keys in useViewSettings.ts, never synced to the account
+const STORAGE_KEY = "calendar-view-mode";
+const CHANGE_EVENT = "calendar-view-mode-change";
+
+// Keeps the choice for the session when storage is unavailable (private mode)
+let memory: CalendarViewMode | null = null;
+
+function readMode(): CalendarViewMode {
+ try {
+ const stored = window.localStorage.getItem(STORAGE_KEY) as CalendarViewMode | null;
+ // No stored value yet (or invalid) — fall back to the session's in-memory choice
+ return stored && AVAILABLE_VIEW_MODES.includes(stored) ? stored : (memory ?? "month");
+ } catch {
+ return memory ?? "month";
+ }
+}
+
+function subscribe(onChange: () => void) {
+ window.addEventListener("storage", onChange);
+ window.addEventListener(CHANGE_EVENT, onChange);
+ return () => {
+ window.removeEventListener("storage", onChange);
+ window.removeEventListener(CHANGE_EVENT, onChange);
+ };
+}
+
+export function useCalendarViewMode() {
+ // The server snapshot keeps the first client render identical to SSR
+ const mode = useSyncExternalStore(subscribe, readMode, () => "month" as const);
+ const setMode = useCallback((next: CalendarViewMode) => {
+ try {
+ window.localStorage.setItem(STORAGE_KEY, next);
+ } catch {
+ memory = next;
+ }
+ window.dispatchEvent(new Event(CHANGE_EVENT));
+ }, []);
+ return [mode, setMode] as const;
+}
diff --git a/hooks/useDialogStates.ts b/hooks/useDialogStates.ts
index 1045ab4..25f7e93 100644
--- a/hooks/useDialogStates.ts
+++ b/hooks/useDialogStates.ts
@@ -13,7 +13,6 @@ export function useDialogStates() {
const [showViewSettingsDialog, setShowViewSettingsDialog] = useState(false);
const [showNotesListDialog, setShowNotesListDialog] = useState(false);
const [showMonthStatsDialog, setShowMonthStatsDialog] = useState(false);
- const [showMonthShiftsDialog, setShowMonthShiftsDialog] = useState(false);
const [showPresetManageDialog, setShowPresetManageDialog] = useState(false);
const [selectedDayDate, setSelectedDayDate] = useState<Date | null>(null);
@@ -39,8 +38,6 @@ export function useDialogStates() {
setShowNotesListDialog,
showMonthStatsDialog,
setShowMonthStatsDialog,
- showMonthShiftsDialog,
- setShowMonthShiftsDialog,
showPresetManageDialog,
setShowPresetManageDialog,
selectedDayDate,
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 61b43c9..459f024 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -264,7 +264,8 @@ export function useShifts(calendarId: string | undefined) {
color: formData.color || s.color,
notes: formData.notes || null,
isAllDay: formData.isAllDay || false,
- presetId: formData.presetId || null,
+ // The edit form never carries presetId — keep the shift's existing value
+ presetId: formData.presetId ?? s.presetId,
updatedAt: new Date(),
}
: s
diff --git a/hooks/useSwipeNavigation.ts b/hooks/useSwipeNavigation.ts
new file mode 100644
index 0000000..503543f
--- /dev/null
+++ b/hooks/useSwipeNavigation.ts
@@ -0,0 +1,35 @@
+"use client";
+
+import { useRef } from "react";
+
+const SWIPE_THRESHOLD_PX = 60;
+// Horizontal movement must clearly dominate vertical, so a page scroll never reads as a swipe
+const AXIS_LOCK_RATIO = 1.5;
+
+interface SwipeHandlers {
+ onTouchStart: (e: React.TouchEvent) => void;
+ onTouchEnd: (e: React.TouchEvent) => void;
+}
+
+/** Horizontal swipe-to-navigate; does not preventDefault, so vertical scrolling is unaffected. */
+export function useSwipeNavigation(onSwipeLeft: () => void, onSwipeRight: () => void): SwipeHandlers {
+ const origin = useRef<{ x: number; y: number } | null>(null);
+
+ return {
+ onTouchStart: (e) => {
+ const touch = e.touches[0];
+ origin.current = touch ? { x: touch.clientX, y: touch.clientY } : null;
+ },
+ onTouchEnd: (e) => {
+ const start = origin.current;
+ origin.current = null;
+ const touch = e.changedTouches[0];
+ if (!start || !touch) return;
+ const deltaX = touch.clientX - start.x;
+ const deltaY = touch.clientY - start.y;
+ if (Math.abs(deltaX) < SWIPE_THRESHOLD_PX || Math.abs(deltaX) < Math.abs(deltaY) * AXIS_LOCK_RATIO) return;
+ if (deltaX < 0) onSwipeLeft();
+ else onSwipeRight();
+ },
+ };
+}
diff --git a/lib/calendar-utils.ts b/lib/calendar-utils.ts
index 41f3292..9719011 100644
--- a/lib/calendar-utils.ts
+++ b/lib/calendar-utils.ts
@@ -17,3 +17,14 @@ export function getCalendarDays(date: Date): Date[] {
end: calendarEnd,
});
}
+
+export function getWeekDays(date: Date): Date[] {
+ return eachDayOfInterval({
+ start: startOfWeek(date, { weekStartsOn: 1 }),
+ end: endOfWeek(date, { weekStartsOn: 1 }),
+ });
+}
+
+export function getMonthDays(date: Date): Date[] {
+ return eachDayOfInterval({ start: startOfMonth(date), end: endOfMonth(date) });
+}
diff --git a/lib/date-utils.ts b/lib/date-utils.ts
index 7accc53..0069ce8 100644
--- a/lib/date-utils.ts
+++ b/lib/date-utils.ts
@@ -1,3 +1,6 @@
+import { endOfWeek, format, startOfWeek } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+
/**
* Converts a Date object to a local date string in YYYY-MM-DD format
* without timezone conversion issues
@@ -34,6 +37,42 @@ export function formatLongDate(
return formatter.format(date);
}
+export type PeriodStep = "month" | "week";
+
+const weekRangeFormatters = new Map<string, Intl.DateTimeFormat>();
+
+/** "8.–14. Sep. 2026"; formatRange collapses the parts both ends share. */
+export function formatWeekRange(start: Date, end: Date, locale: string, withYear = true): string {
+ const key = `${locale}|${withYear}`;
+ let formatter = weekRangeFormatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(locale, {
+ day: "numeric",
+ month: "short",
+ ...(withYear ? { year: "numeric" as const } : {}),
+ });
+ weekRangeFormatters.set(key, formatter);
+ }
+ return formatter.formatRange(start, end);
+}
+
+/** Stepper and title caption: the month name, or the Monday–Sunday range around `date`. */
+export function formatPeriodCaption(
+ date: Date,
+ step: PeriodStep,
+ locale: string,
+ { compact = false }: { compact?: boolean } = {}
+): string {
+ if (step === "month") return format(date, "LLLL yyyy", { locale: getDateLocale(locale) });
+ const start = startOfWeek(date, { weekStartsOn: 1 });
+ const end = endOfWeek(date, { weekStartsOn: 1 });
+ // Compact drops the year while the whole week lies in the current one
+ const thisYear = new Date().getFullYear();
+ const withYear =
+ !compact || start.getFullYear() !== thisYear || end.getFullYear() !== thisYear;
+ return formatWeekRange(start, end, locale, withYear);
+}
+
const LOCAL_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
/**
diff --git a/messages/cs.json b/messages/cs.json
index dc9f739..cdb4330 100644
--- a/messages/cs.json
+++ b/messages/cs.json
@@ -684,6 +684,20 @@
"calendarView": {
"previousMonth": "Předchozí měsíc",
"nextMonth": "Další měsíc",
+ "previousWeek": "Předchozí týden",
+ "nextWeek": "Další týden",
+ "viewMode": "Zobrazení",
+ "viewMonth": "Měsíc",
+ "viewWeek": "Týden",
+ "viewList": "Seznam",
+ "thisWeek": "Tento týden",
+ "listSearchPlaceholder": "Hledat směny a poznámky",
+ "listClearSearch": "Vymazat hledání",
+ "listNoMatches": "Tomuto hledání nebo filtru nic neodpovídá.",
+ "listWithoutPreset": "Bez šablony",
+ "listSortPinnedHint": "Řazení určuje tento kalendář.",
+ "nextShift": "Další směna",
+ "noUpcomingShift": "Žádná nadcházející směna",
"today": "Dnes",
"tomorrow": "Zítra",
"yesterday": "Včera",
diff --git a/messages/de.json b/messages/de.json
index 23da259..9d90af8 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -684,6 +684,20 @@
"calendarView": {
"previousMonth": "Vorheriger Monat",
"nextMonth": "Nächster Monat",
+ "previousWeek": "Vorherige Woche",
+ "nextWeek": "Nächste Woche",
+ "viewMode": "Ansicht",
+ "viewMonth": "Monat",
+ "viewWeek": "Woche",
+ "viewList": "Liste",
+ "thisWeek": "Diese Woche",
+ "listSearchPlaceholder": "Schichten und Notizen durchsuchen",
+ "listClearSearch": "Suche leeren",
+ "listNoMatches": "Keine Treffer für diese Suche oder diesen Filter.",
+ "listWithoutPreset": "Ohne Vorlage",
+ "listSortPinnedHint": "Dieser Kalender legt die Sortierung fest.",
+ "nextShift": "Nächste Schicht",
+ "noUpcomingShift": "Keine anstehende Schicht",
"today": "Heute",
"tomorrow": "Morgen",
"yesterday": "Gestern",
diff --git a/messages/en.json b/messages/en.json
index ffbc01e..9f66ab9 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -684,6 +684,20 @@
"calendarView": {
"previousMonth": "Previous month",
"nextMonth": "Next month",
+ "previousWeek": "Previous week",
+ "nextWeek": "Next week",
+ "viewMode": "View",
+ "viewMonth": "Month",
+ "viewWeek": "Week",
+ "viewList": "List",
+ "thisWeek": "This week",
+ "listSearchPlaceholder": "Search shifts and notes",
+ "listClearSearch": "Clear search",
+ "listNoMatches": "Nothing matches this search or filter.",
+ "listWithoutPreset": "No preset",
+ "listSortPinnedHint": "This calendar sets the sort order.",
+ "nextShift": "Next shift",
+ "noUpcomingShift": "No upcoming shift",
"today": "Today",
"tomorrow": "Tomorrow",
"yesterday": "Yesterday",
diff --git a/messages/es.json b/messages/es.json
index 2cbe46c..51b85e2 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -684,6 +684,20 @@
"calendarView": {
"previousMonth": "Mes anterior",
"nextMonth": "Mes siguiente",
+ "previousWeek": "Semana anterior",
+ "nextWeek": "Semana siguiente",
+ "viewMode": "Vista",
+ "viewMonth": "Mes",
+ "viewWeek": "Semana",
+ "viewList": "Lista",
+ "thisWeek": "Esta semana",
+ "listSearchPlaceholder": "Buscar turnos y notas",
+ "listClearSearch": "Borrar búsqueda",
+ "listNoMatches": "Nada coincide con esta búsqueda o filtro.",
+ "listWithoutPreset": "Sin plantilla",
+ "listSortPinnedHint": "Este calendario define el orden.",
+ "nextShift": "Próximo turno",
+ "noUpcomingShift": "Ningún turno próximo",
"today": "Hoy",
"tomorrow": "Mañana",
"yesterday": "Ayer",
diff --git a/messages/fr.json b/messages/fr.json
index 3af219e..1570c41 100755
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -684,6 +684,20 @@
"calendarView": {
"previousMonth": "Mois précédent",
"nextMonth": "Mois suivant",
+ "previousWeek": "Semaine précédente",
+ "nextWeek": "Semaine suivante",
+ "viewMode": "Vue",
+ "viewMonth": "Mois",
+ "viewWeek": "Semaine",
+ "viewList": "Liste",
+ "thisWeek": "Cette semaine",
+ "listSearchPlaceholder": "Rechercher des services et des notes",
+ "listClearSearch": "Effacer la recherche",
+ "listNoMatches": "Aucun résultat pour cette recherche ou ce filtre.",
+ "listWithoutPreset": "Sans modèle",
+ "listSortPinnedHint": "Ce calendrier définit le tri.",
+ "nextShift": "Prochain service",
+ "noUpcomingShift": "Aucun service à venir",
"today": "Aujourd’hui",
"tomorrow": "Demain",
"yesterday": "Hier",
diff --git a/messages/it.json b/messages/it.json
index 0becc9e..9b5b61e 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -684,6 +684,20 @@
"calendarView": {
"previousMonth": "Mese precedente",
"nextMonth": "Mese successivo",
+ "previousWeek": "Settimana precedente",
+ "nextWeek": "Settimana successiva",
+ "viewMode": "Vista",
+ "viewMonth": "Mese",
+ "viewWeek": "Settimana",
+ "viewList": "Elenco",
+ "thisWeek": "Questa settimana",
+ "listSearchPlaceholder": "Cerca turni e note",
+ "listClearSearch": "Cancella ricerca",
+ "listNoMatches": "Nessun risultato per questa ricerca o filtro.",
+ "listWithoutPreset": "Senza modello",
+ "listSortPinnedHint": "Questo calendario definisce l’ordinamento.",
+ "nextShift": "Prossimo turno",
+ "noUpcomingShift": "Nessun turno in programma",
"today": "Oggi",
"tomorrow": "Domani",
"yesterday": "Ieri",