Skip to content

Your favorite shift management application!

chore: stop tracking superpowers specs and plans

panteLx1a08ce64a402
diff --git a/.gitignore b/.gitignore
index bdb5403..eb3217c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -83,3 +83,6 @@ public/workbox-*.js.map
.claude/
.playwright-mcp/
+
+# Superpowers specs and plans (local planning artifacts, not part of the product docs)
+docs/superpowers/
diff --git a/docs/superpowers/plans/2026-09-15-split-shifts.md b/docs/superpowers/plans/2026-09-15-split-shifts.md
deleted file mode 100644
index d72da1a..0000000
--- a/docs/superpowers/plans/2026-09-15-split-shifts.md
+++ /dev/null
@@ -1,2203 +0,0 @@
-# Split Shifts 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:** Let a shift (and a preset) have more than one time range on the same day — e.g. `06:00–10:00` and `15:00–21:00` in one duty — gated per calendar behind an owner/admin-controlled toggle, without changing behavior for the (majority) single-range case.
-
-**Architecture:** The primary time range stays on `shifts.startTime`/`endTime` and `shiftPresets.startTime`/`endTime` exactly as today. Two new child tables (`shiftTimeSegments`, `presetTimeSegments`) hold only the *additional* ranges, following the existing `shiftSignups` one-to-many-on-parent-id pattern. A new `calendars.splitShiftsEnabled` boolean (default `false`) gates the feature per calendar, modeled byte-for-byte on the existing `calendars.signupsEnabled` master switch.
-
-**Tech Stack:** Next.js 16 (App Router) API routes, Drizzle ORM / SQLite (better-sqlite3), React 19 client components, TanStack Query, next-intl.
-
-**Spec:** `docs/superpowers/specs/2026-09-15-split-shifts-design.md`
-
-## Global Constraints
-
-- No unit-test framework in this repo. Verification is `npx tsc --noEmit` (fast, run after almost every step) and the full `npm test` (lint + build + i18n) at task boundaries — see `CLAUDE.md`.
-- Never write raw `ALTER TABLE` SQL by hand — always edit `lib/db/schema.ts` then run `npm run db:generate` (creates the `.sql`, snapshot, and `_journal.json` entry together) followed by `npm run db:migrate`.
-- `messages/de.json` is the source of truth for i18n; add a key there first, then mirror the same key into `en.json`, `es.json`, `fr.json`, `it.json`, `cs.json` before running `npm run i18n`.
-- `startTime`/`endTime` on `shifts`/`shiftPresets` must keep meaning exactly what they mean today (the primary/first range) — every task must stay backward compatible for code that only reads those two fields.
-- Segments are validated (chronological, non-overlapping, same-day, no midnight wraparound) only when there is more than one range; a single range keeps 100% of its current behavior, including overnight shifts.
-- Follow existing code style: no comments unless they explain a non-obvious constraint; German UI strings mirror the tone of neighboring keys (see `sharingSheet.signupsEnabledLabel`/`Desc` for the reference tone).
-
----
-
-### Task 1: Schema, migration, and shared types
-
-**Files:**
-- Modify: `lib/db/schema.ts`
-- Modify: `lib/types.ts`
-- Modify: `hooks/useCalendars.ts`
-- Create (generated): `drizzle/00XX_*.sql`, `drizzle/meta/00XX_snapshot.json`, updated `drizzle/meta/_journal.json`
-
-**Interfaces:**
-- Produces: `shiftTimeSegments` table (`id`, `shiftId`, `startTime`, `endTime`, `createdAt`), `presetTimeSegments` table (`id`, `presetId`, `startTime`, `endTime`, `createdAt`), `calendars.splitShiftsEnabled: boolean`, `shiftsRelations.segments` / `shiftPresetsRelations.segments` (Drizzle relations), `ShiftWithCalendar.segments?: { startTime: string; endTime: string }[]`, `CalendarWithCount.splitShiftsEnabled?: boolean`, `CalendarUpdateInput.splitShiftsEnabled?: boolean`.
-
-- [ ] **Step 1: Add the two child tables to the schema**
-
-In `lib/db/schema.ts`, add right after the `shiftPresets` table definition (before `calendarNotes`):
-
-```ts
-export const shiftTimeSegments = sqliteTable(
- "shift_time_segments",
- {
- id: text("id")
- .primaryKey()
- .$defaultFn(() => crypto.randomUUID()),
- shiftId: text("shift_id")
- .notNull()
- .references(() => shifts.id, { onDelete: "cascade" }),
- startTime: text("start_time").notNull(),
- endTime: text("end_time").notNull(),
- createdAt: integer("created_at", { mode: "timestamp" })
- .notNull()
- .default(sql`CURRENT_TIMESTAMP`),
- },
- (table) => [index("shift_time_segments_shiftId_idx").on(table.shiftId)]
-);
-
-export const presetTimeSegments = sqliteTable(
- "preset_time_segments",
- {
- id: text("id")
- .primaryKey()
- .$defaultFn(() => crypto.randomUUID()),
- presetId: text("preset_id")
- .notNull()
- .references(() => shiftPresets.id, { onDelete: "cascade" }),
- startTime: text("start_time").notNull(),
- endTime: text("end_time").notNull(),
- createdAt: integer("created_at", { mode: "timestamp" })
- .notNull()
- .default(sql`CURRENT_TIMESTAMP`),
- },
- (table) => [index("preset_time_segments_presetId_idx").on(table.presetId)]
-);
-```
-
-- [ ] **Step 2: Add `splitShiftsEnabled` to `calendars`**
-
-In the `calendars` table definition, right after the existing `signupsEnabled` field:
-
-```ts
- // Master switch for split shifts (multiple time ranges per shift/preset)
- // on this calendar. Owner/admin only; off hides extra ranges everywhere,
- // same contract as signupsEnabled above.
- splitShiftsEnabled: integer("split_shifts_enabled", { mode: "boolean" })
- .notNull()
- .default(false),
-```
-
-- [ ] **Step 3: Wire up relations**
-
-In `shiftsRelations`, add a `segments` relation next to `signups`:
-
-```ts
-export const shiftsRelations = relations(shifts, ({ one, many }) => ({
- calendar: one(calendars, {
- fields: [shifts.calendarId],
- references: [calendars.id],
- }),
- preset: one(shiftPresets, {
- fields: [shifts.presetId],
- references: [shiftPresets.id],
- }),
- signups: many(shiftSignups),
- segments: many(shiftTimeSegments),
- creator: one(user, {
- fields: [shifts.createdBy],
- references: [user.id],
- }),
-}));
-```
-
-In `shiftPresetsRelations`, add the equivalent (it currently only has `one`, so switch its factory to also destructure `many`):
-
-```ts
-export const shiftPresetsRelations = relations(shiftPresets, ({ one, many }) => ({
- calendar: one(calendars, {
- fields: [shiftPresets.calendarId],
- references: [calendars.id],
- }),
- segments: many(presetTimeSegments),
- creator: one(user, {
- fields: [shiftPresets.createdBy],
- references: [user.id],
- }),
-}));
-```
-
-Add the two matching one-side relations, anywhere near the other `*Relations` exports:
-
-```ts
-export const shiftTimeSegmentsRelations = relations(shiftTimeSegments, ({ one }) => ({
- shift: one(shifts, {
- fields: [shiftTimeSegments.shiftId],
- references: [shifts.id],
- }),
-}));
-
-export const presetTimeSegmentsRelations = relations(presetTimeSegments, ({ one }) => ({
- preset: one(shiftPresets, {
- fields: [presetTimeSegments.presetId],
- references: [shiftPresets.id],
- }),
-}));
-```
-
-- [ ] **Step 4: Generate and apply the migration**
-
-Run:
-```bash
-npm run db:generate
-npm run db:migrate
-```
-Expected: a new `drizzle/00XX_<name>.sql` containing two `CREATE TABLE` statements and one `ALTER TABLE calendars ADD split_shifts_enabled ...` statement, plus an updated `drizzle/meta/_journal.json` with one new entry. `db:migrate` exits 0.
-
-- [ ] **Step 5: Type-check**
-
-Run: `npx tsc --noEmit`
-Expected: no new errors (the new tables/relations are additive).
-
-- [ ] **Step 6: Update `lib/types.ts`**
-
-Add a `TimeRange` re-export-friendly field to `ShiftWithCalendar` and `splitShiftsEnabled` to `CalendarWithCount`:
-
-```ts
-export interface CalendarWithCount {
- id: string;
- name: string;
- color: string;
- ownerId?: string | null;
- guestBundleId?: string | null;
- signupsEnabled?: boolean;
- splitShiftsEnabled?: boolean;
- /** The calendar's own view; null means everyone sees their personal view */
- viewSettings?: CalendarViewSettings | null;
- createdAt: Date | null;
- updatedAt: Date | null;
- _count?: number;
- capabilities?: Capability[];
- bundle?: CalendarBundleRef | null;
- isSubscribed?: boolean;
- subscriptionSource?: "guest" | "shared" | "token";
- canSignUpSelf?: boolean;
- canSignUpOthers?: boolean;
-}
-
-export interface ShiftWithCalendar {
- id: string;
- calendarId: string;
- presetId?: string | null;
- calendar?: {
- id: string;
- name: string;
- color: string;
- };
- date: Date | null;
- startTime: string;
- endTime: string;
- title: string;
- color: string;
- notes?: string | null;
- isAllDay?: boolean;
- syncedFromExternal?: boolean;
- externalSyncId?: string | null;
- signupCapacity?: number | null;
- signups?: ShiftSignupUser[];
- /** Additional time ranges beyond startTime/endTime (split shifts). Empty/undefined for a normal shift. */
- segments?: { startTime: string; endTime: string }[];
- createdBy?: string | null;
- createdAt: Date | null;
- updatedAt: Date | null;
-}
-```
-
-- [ ] **Step 7: Update `hooks/useCalendars.ts`**
-
-Add the field to `CalendarUpdateInput`:
-
-```ts
-export interface CalendarUpdateInput {
- name?: string;
- color?: string;
- guestBundleId?: string | null;
- viewSettings?: CalendarViewSettings | null;
- signupsEnabled?: boolean;
- splitShiftsEnabled?: boolean;
-}
-```
-
-- [ ] **Step 8: Type-check again**
-
-Run: `npx tsc --noEmit`
-Expected: clean.
-
-- [ ] **Step 9: Commit**
-
-```bash
-git add lib/db/schema.ts lib/types.ts hooks/useCalendars.ts drizzle
-git commit -m "feat(db): add split-shift time segments and calendar toggle"
-```
-
----
-
-### Task 2: Client-safe time-range logic
-
-**Files:**
-- Create: `lib/time-ranges.ts`
-
-**Interfaces:**
-- Consumes: nothing project-specific (pure functions).
-- Produces: `TimeRange` type, `toTimeRanges(entity: { startTime: string; endTime: string; segments?: TimeRange[] }): TimeRange[]`, `validateTimeRanges(ranges: TimeRange[]): TimeRangeError | null`, `TimeRangeError` union, `sumRangeDurations(ranges: TimeRange[]): number`.
-
-- [ ] **Step 1: Write the module**
-
-```ts
-import { calculateShiftDuration } from "@/lib/date-utils";
-
-export interface TimeRange {
- startTime: string;
- endTime: string;
-}
-
-export type TimeRangeError = "invalid_format" | "overnight_segment" | "overlap";
-
-const TIME_PATTERN = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
-
-function toMinutes(time: string): number {
- const [hours, minutes] = time.split(":").map(Number);
- return hours * 60 + minutes;
-}
-
-/** Reassembles the primary range plus any extra segments into one ordered-by-input list. */
-export function toTimeRanges(entity: {
- startTime: string;
- endTime: string;
- segments?: TimeRange[];
-}): TimeRange[] {
- return [
- { startTime: entity.startTime, endTime: entity.endTime },
- ...(entity.segments ?? []),
- ];
-}
-
-/**
- * Validates a full list of ranges for a shift/preset. A single range is
- * always valid here (including one that crosses midnight — unchanged
- * existing behavior); chronological order, non-overlap and same-day-only
- * are enforced only once there is more than one range.
- */
-export function validateTimeRanges(ranges: TimeRange[]): TimeRangeError | null {
- for (const range of ranges) {
- if (!TIME_PATTERN.test(range.startTime) || !TIME_PATTERN.test(range.endTime)) {
- return "invalid_format";
- }
- }
-
- if (ranges.length <= 1) return null;
-
- for (const range of ranges) {
- if (toMinutes(range.endTime) <= toMinutes(range.startTime)) {
- return "overnight_segment";
- }
- }
-
- const sorted = [...ranges].sort((a, b) => toMinutes(a.startTime) - toMinutes(b.startTime));
- for (let i = 1; i < sorted.length; i++) {
- if (toMinutes(sorted[i].startTime) < toMinutes(sorted[i - 1].endTime)) {
- return "overlap";
- }
- }
-
- return null;
-}
-
-/** Total duration across all ranges, in minutes. */
-export function sumRangeDurations(ranges: TimeRange[]): number {
- return ranges.reduce(
- (total, range) => total + calculateShiftDuration(range.startTime, range.endTime),
- 0
- );
-}
-```
-
-- [ ] **Step 2: Type-check**
-
-Run: `npx tsc --noEmit`
-Expected: clean (this file has no callers yet, so it must compile standalone).
-
-- [ ] **Step 3: Sanity-check the validation logic with a throwaway script**
-
-Run:
-```bash
-npx tsx -e "
-import { validateTimeRanges } from './lib/time-ranges';
-console.log(validateTimeRanges([{ startTime: '06:00', endTime: '10:00' }])); // null
-console.log(validateTimeRanges([{ startTime: '22:00', endTime: '06:00' }])); // null (single range, overnight ok)
-console.log(validateTimeRanges([{ startTime: '06:00', endTime: '10:00' }, { startTime: '15:00', endTime: '21:00' }])); // null
-console.log(validateTimeRanges([{ startTime: '15:00', endTime: '21:00' }, { startTime: '06:00', endTime: '10:00' }])); // null (order-independent input)
-console.log(validateTimeRanges([{ startTime: '06:00', endTime: '10:00' }, { startTime: '09:00', endTime: '12:00' }])); // 'overlap'
-console.log(validateTimeRanges([{ startTime: '22:00', endTime: '06:00' }, { startTime: '08:00', endTime: '12:00' }])); // 'overnight_segment'
-"
-```
-Expected output, one value per line: `null`, `null`, `null`, `null`, `overlap`, `overnight_segment`. If any line differs, fix `validateTimeRanges` before continuing.
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add lib/time-ranges.ts
-git commit -m "feat: add client-safe time-range validation and duration helpers"
-```
-
----
-
-### Task 3: Server-side segment persistence helpers
-
-**Files:**
-- Create: `lib/shift-time-ranges.ts`
-
-**Interfaces:**
-- Consumes: `TimeRange` from `lib/time-ranges.ts`; `db`, `shiftTimeSegments`, `presetTimeSegments` from `lib/db`/`lib/db/schema`.
-- Produces: `replaceShiftSegments(tx, shiftId, ranges)`, `replacePresetSegments(tx, presetId, ranges)`, `withShiftSegments<T extends {id: string}>(rows: T[])`, `withPresetSegments<T extends {id: string}>(rows: T[])`.
-
-- [ ] **Step 1: Write the module**
-
-```ts
-import { db } from "@/lib/db";
-import { shiftTimeSegments, presetTimeSegments } from "@/lib/db/schema";
-import { eq, inArray } from "drizzle-orm";
-import type { TimeRange } from "@/lib/time-ranges";
-
-type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
-
-/** Replaces every extra segment for one shift (delete-then-insert), inside an existing transaction. */
-export function replaceShiftSegments(tx: Tx, shiftId: string, ranges: TimeRange[]): void {
- tx.delete(shiftTimeSegments).where(eq(shiftTimeSegments.shiftId, shiftId)).run();
- if (ranges.length > 0) {
- tx.insert(shiftTimeSegments)
- .values(ranges.map((r) => ({ shiftId, startTime: r.startTime, endTime: r.endTime })))
- .run();
- }
-}
-
-/** Replaces every extra segment for one preset (delete-then-insert), inside an existing transaction. */
-export function replacePresetSegments(tx: Tx, presetId: string, ranges: TimeRange[]): void {
- tx.delete(presetTimeSegments).where(eq(presetTimeSegments.presetId, presetId)).run();
- if (ranges.length > 0) {
- tx.insert(presetTimeSegments)
- .values(ranges.map((r) => ({ presetId, startTime: r.startTime, endTime: r.endTime })))
- .run();
- }
-}
-
-/** Attaches each shift's extra segments without N+1 queries. */
-export async function withShiftSegments<T extends { id: string }>(
- rows: T[]
-): Promise<(T & { segments: TimeRange[] })[]> {
- if (rows.length === 0) return [];
-
- const allSegments = await db.query.shiftTimeSegments.findMany({
- where: inArray(
- shiftTimeSegments.shiftId,
- rows.map((r) => r.id)
- ),
- orderBy: (segments, { asc }) => [asc(segments.startTime)],
- });
-
- const byShiftId = new Map<string, TimeRange[]>();
- for (const segment of allSegments) {
- const list = byShiftId.get(segment.shiftId) ?? [];
- list.push({ startTime: segment.startTime, endTime: segment.endTime });
- byShiftId.set(segment.shiftId, list);
- }
-
- return rows.map((row) => ({ ...row, segments: byShiftId.get(row.id) ?? [] }));
-}
-
-/** Attaches each preset's extra segments without N+1 queries. */
-export async function withPresetSegments<T extends { id: string }>(
- rows: T[]
-): Promise<(T & { segments: TimeRange[] })[]> {
- if (rows.length === 0) return [];
-
- const allSegments = await db.query.presetTimeSegments.findMany({
- where: inArray(
- presetTimeSegments.presetId,
- rows.map((r) => r.id)
- ),
- orderBy: (segments, { asc }) => [asc(segments.startTime)],
- });
-
- const byPresetId = new Map<string, TimeRange[]>();
- for (const segment of allSegments) {
- const list = byPresetId.get(segment.presetId) ?? [];
- list.push({ startTime: segment.startTime, endTime: segment.endTime });
- byPresetId.set(segment.presetId, list);
- }
-
- return rows.map((row) => ({ ...row, segments: byPresetId.get(row.id) ?? [] }));
-}
-```
-
-Note: `tx.delete(...).run()` / `.insert(...).run()` — the `better-sqlite3` Drizzle driver's synchronous query builder exposes `.run()` for statements without a `.returning()`; existing transaction code in `app/api/calendars/route.ts` uses the same synchronous `db.transaction((tx) => {...})` shape without `await` inside.
-
-- [ ] **Step 2: Type-check**
-
-Run: `npx tsc --noEmit`
-Expected: clean. If `Tx` inference fails, replace it with the exact type Drizzle exports for a better-sqlite3 transaction callback parameter (check `app/api/calendars/route.ts`'s `db.transaction((tx) => {` for the inferred type via hover/`tsc`, since that file already uses one) rather than leaving `tx: any`.
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add lib/shift-time-ranges.ts
-git commit -m "feat: add server-side segment persistence helpers"
-```
-
----
-
-### Task 4: Shifts API — read, create, update
-
-**Files:**
-- Modify: `app/api/shifts/route.ts`
-- Modify: `app/api/shifts/[id]/route.ts`
-
-**Interfaces:**
-- Consumes: `toTimeRanges`, `validateTimeRanges` (`lib/time-ranges.ts`); `replaceShiftSegments`, `withShiftSegments` (`lib/shift-time-ranges.ts`).
-- Produces: shift API responses gain `segments: TimeRange[]`; `POST`/`PUT` accept an optional `segments` field in the body.
-
-- [ ] **Step 1: `GET /api/shifts` — attach segments**
-
-In `app/api/shifts/route.ts`, wrap both returned results through `withShiftSegments`. Replace:
-
-```ts
- const result = await query.where(
- and(
- eq(shifts.calendarId, calendarId),
- gte(shifts.date, startOfDay),
- lte(shifts.date, endOfDay),
- or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
- )
- );
- return NextResponse.json(await withSignups(result));
- }
-
- const result = await query.where(
- and(
- eq(shifts.calendarId, calendarId),
- or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
- )
- );
- return NextResponse.json(await withSignups(result));
-```
-
-with:
-
-```ts
- const result = await query.where(
- and(
- eq(shifts.calendarId, calendarId),
- gte(shifts.date, startOfDay),
- lte(shifts.date, endOfDay),
- or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
- )
- );
- return NextResponse.json(await withShiftSegments(await withSignups(result)));
- }
-
- const result = await query.where(
- and(
- eq(shifts.calendarId, calendarId),
- or(isNull(shifts.externalSyncId), eq(externalSyncs.isHidden, false))
- )
- );
- return NextResponse.json(await withShiftSegments(await withSignups(result)));
-```
-
-Add the import:
-
-```ts
-import { withShiftSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
-import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
-```
-
-(`withPresetSegments` is needed in Step 2 below, for reading a preset's own segments when stamping.)
-
-- [ ] **Step 2: `POST /api/shifts` — validate and persist segments**
-
-Replace the body destructuring:
-
-```ts
- const {
- calendarId,
- date,
- startTime,
- endTime,
- title,
- color,
- notes,
- presetId,
- isAllDay,
- isSecondary,
- signupCapacity,
- signupUserIds,
- } = body;
-```
-
-with:
-
-```ts
- const {
- calendarId,
- date,
- startTime,
- endTime,
- title,
- color,
- notes,
- presetId,
- isAllDay,
- isSecondary,
- signupCapacity,
- signupUserIds,
- segments: requestedSegments,
- } = body;
-```
-
-Change the `insertValues` block so both branches also produce a `segmentsToPersist: TimeRange[]`. Replace the whole `if (access.can("createShift")) { ... } else { ... }` block with:
-
-```ts
- let insertValues: {
- title: string;
- startTime: string;
- endTime: string;
- color: string;
- notes: string | null;
- isAllDay: boolean;
- };
- let segmentsToPersist: TimeRange[] = [];
-
- if (access.can("createShift")) {
- if (presetId) {
- const [preset] = await db
- .select()
- .from(shiftPresets)
- .where(
- and(
- eq(shiftPresets.id, presetId),
- eq(shiftPresets.calendarId, calendarId)
- )
- );
- if (!preset) {
- return NextResponse.json(
- { error: "Preset not found" },
- { status: 404 }
- );
- }
- }
- insertValues = {
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color: color || "#3b82f6",
- notes: notes || null,
- isAllDay: isAllDay || false,
- };
-
- if (!isAllDay) {
- const rawSegments: TimeRange[] = Array.isArray(requestedSegments)
- ? requestedSegments
- : [];
- if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
- return NextResponse.json(
- { error: "Split shifts are not enabled for this calendar" },
- { status: 400 }
- );
- }
- const allRanges = toTimeRanges({ ...insertValues, segments: rawSegments });
- const validationError = validateTimeRanges(allRanges);
- if (validationError) {
- return NextResponse.json({ error: validationError }, { status: 400 });
- }
- segmentsToPersist = rawSegments;
- }
- } else {
- if (!presetId) {
- return NextResponse.json(
- { error: "presetId is required" },
- { status: 400 }
- );
- }
- const [preset] = await db
- .select()
- .from(shiftPresets)
- .where(
- and(
- eq(shiftPresets.id, presetId),
- eq(shiftPresets.calendarId, calendarId)
- )
- );
- if (!preset) {
- return NextResponse.json(
- { error: "Preset not found" },
- { status: 404 }
- );
- }
- insertValues = {
- title: preset.title,
- startTime: preset.isAllDay ? "00:00" : preset.startTime,
- endTime: preset.isAllDay ? "23:59" : preset.endTime,
- color: preset.color,
- notes: preset.notes,
- isAllDay: preset.isAllDay,
- };
- if (!preset.isAllDay && calendar.splitShiftsEnabled) {
- const [presetWithSegments] = await withPresetSegments([preset]);
- segmentsToPersist = presetWithSegments.segments;
- }
- }
-```
-
-- [ ] **Step 3: Persist the shift and its segments in one transaction**
-
-Replace the plain `db.insert(shifts)...returning()` call:
-
-```ts
- const [shift] = await db
- .insert(shifts)
- .values({
- calendarId,
- presetId: presetId || null,
- date: parsedDate,
- ...insertValues,
- isSecondary: isSecondary || false,
- signupCapacity:
- typeof signupCapacity === "number" ? signupCapacity : null,
- createdBy: user?.id ?? null,
- createdAt: new Date(),
- updatedAt: new Date(),
- })
- .returning();
-```
-
-with:
-
-```ts
- const shift = db.transaction((tx) => {
- const inserted = tx
- .insert(shifts)
- .values({
- calendarId,
- presetId: presetId || null,
- date: parsedDate,
- ...insertValues,
- isSecondary: isSecondary || false,
- signupCapacity:
- typeof signupCapacity === "number" ? signupCapacity : null,
- createdBy: user?.id ?? null,
- createdAt: new Date(),
- updatedAt: new Date(),
- })
- .returning()
- .get();
- replaceShiftSegments(tx, inserted.id, segmentsToPersist);
- return inserted;
- });
-```
-
-Update the final response to include segments:
-
-```ts
- return NextResponse.json(
- { ...shift, calendar, signups, segments: segmentsToPersist },
- { status: 201 }
- );
-```
-
-- [ ] **Step 4: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/shifts/route.ts`
-Expected: clean (`.returning().get()` is the same synchronous single-row pattern already used in `app/api/calendars/route.ts`'s `db.transaction((tx) => {...})` block).
-
-- [ ] **Step 5: `GET /api/shifts/[id]` — attach segments**
-
-In `app/api/shifts/[id]/route.ts`, add the import `import { withShiftSegments } from "@/lib/shift-time-ranges";` and change the `GET` handler's return:
-
-```ts
- return NextResponse.json(result[0]);
-```
-to:
-```ts
- const [withSegments] = await withShiftSegments([result[0]]);
- return NextResponse.json(withSegments);
-```
-
-- [ ] **Step 6: `PUT /api/shifts/[id]` — validate and persist segments on update**
-
-Add imports:
-
-```ts
-import { replaceShiftSegments, withShiftSegments } from "@/lib/shift-time-ranges";
-import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
-```
-
-Before the existing `db.update(shifts)...` call, insert validation and figure out the calendar's `splitShiftsEnabled`:
-
-```ts
- const nextStartTime = body.startTime ?? existingShift.startTime;
- const nextEndTime = body.endTime ?? existingShift.endTime;
- const nextIsAllDay = body.isAllDay ?? existingShift.isAllDay;
-
- let nextSegments: TimeRange[] | undefined;
- if (body.segments !== undefined) {
- const rawSegments: TimeRange[] = Array.isArray(body.segments) ? body.segments : [];
- if (!nextIsAllDay) {
- const [calendar] = await db
- .select()
- .from(calendars)
- .where(eq(calendars.id, existingShift.calendarId));
- if (rawSegments.length > 0 && !calendar?.splitShiftsEnabled) {
- return NextResponse.json(
- { error: "Split shifts are not enabled for this calendar" },
- { status: 400 }
- );
- }
- const allRanges = toTimeRanges({
- startTime: nextStartTime,
- endTime: nextEndTime,
- segments: rawSegments,
- });
- const validationError = validateTimeRanges(allRanges);
- if (validationError) {
- return NextResponse.json({ error: validationError }, { status: 400 });
- }
- }
- nextSegments = nextIsAllDay ? [] : rawSegments;
- }
-```
-
-(`calendars` needs to be imported in this file — add it to the existing `import { calendars, shiftPresets, shifts } from "@/lib/db/schema";` line.)
-
-Replace the update call:
-
-```ts
- const [updatedShift] = await db
- .update(shifts)
- .set({
- date,
- startTime: body.startTime ?? existingShift.startTime,
- endTime: body.endTime ?? existingShift.endTime,
- title: body.title ?? existingShift.title,
- color: body.color ?? existingShift.color,
- notes: body.notes ?? existingShift.notes,
- isAllDay: body.isAllDay ?? existingShift.isAllDay,
- presetId: body.presetId ?? existingShift.presetId,
- signupCapacity:
- typeof body.signupCapacity === "number"
- ? body.signupCapacity
- : body.signupCapacity === null
- ? null
- : existingShift.signupCapacity,
- updatedAt: new Date(),
- })
- .where(eq(shifts.id, id))
- .returning();
-
- return NextResponse.json(updatedShift);
-```
-
-with:
-
-```ts
- const updatedShift = db.transaction((tx) => {
- const updated = tx
- .update(shifts)
- .set({
- date,
- startTime: nextStartTime,
- endTime: nextEndTime,
- title: body.title ?? existingShift.title,
- color: body.color ?? existingShift.color,
- notes: body.notes ?? existingShift.notes,
- isAllDay: nextIsAllDay,
- presetId: body.presetId ?? existingShift.presetId,
- signupCapacity:
- typeof body.signupCapacity === "number"
- ? body.signupCapacity
- : body.signupCapacity === null
- ? null
- : existingShift.signupCapacity,
- updatedAt: new Date(),
- })
- .where(eq(shifts.id, id))
- .returning()
- .get();
- if (nextSegments !== undefined) {
- replaceShiftSegments(tx, id, nextSegments);
- }
- return updated;
- });
-
- const [withSegments] = await withShiftSegments([updatedShift]);
- return NextResponse.json(withSegments);
-```
-
-- [ ] **Step 7: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/shifts/[id]/route.ts app/api/shifts/route.ts`
-Expected: clean.
-
-- [ ] **Step 8: Manual smoke test against the running dev server**
-
-Run `npm run dev` in the background, then (with a real session cookie or `AUTH_ENABLED=false`) exercise both routes:
-```bash
-curl -s -X POST http://localhost:3000/api/shifts -H "Content-Type: application/json" \
- -d '{"calendarId":"<id>","date":"2026-09-20","startTime":"06:00","endTime":"10:00","title":"Test","segments":[{"startTime":"15:00","endTime":"21:00"}]}' | jq .
-```
-Expected: `201`, response contains `startTime: "06:00"`, `endTime: "10:00"`, `segments: [{"startTime":"15:00","endTime":"21:00"}]` — unless the target calendar has `splitShiftsEnabled: false`, in which case expect a `400` with `"Split shifts are not enabled for this calendar"` (this is expected until Task 6 lets you flip the toggle; for now confirm the 400 path works, then re-test the 201 path after Task 6/9 are done and the toggle is on).
-
-- [ ] **Step 9: Commit**
-
-```bash
-git add app/api/shifts/route.ts app/api/shifts/[id]/route.ts
-git commit -m "feat(api): validate and persist shift time segments"
-```
-
----
-
-### Task 5: Presets API — read, create, update (with cascade)
-
-**Files:**
-- Modify: `app/api/presets/route.ts`
-- Modify: `app/api/presets/[id]/route.ts`
-
-**Interfaces:**
-- Consumes: `toTimeRanges`, `validateTimeRanges` (`lib/time-ranges.ts`); `replacePresetSegments`, `replaceShiftSegments`, `withPresetSegments` (`lib/shift-time-ranges.ts`).
-- Produces: preset API responses gain `segments: TimeRange[]`; `POST`/`PATCH` accept an optional `segments` field.
-
-- [ ] **Step 1: `GET /api/presets` — attach segments**
-
-Add import `import { withPresetSegments } from "@/lib/shift-time-ranges";`. Replace:
-
-```ts
- const presets = await db
- .select()
- .from(shiftPresets)
- .where(eq(shiftPresets.calendarId, calendarId))
- .orderBy(asc(shiftPresets.order));
- return NextResponse.json(presets);
-```
-
-with:
-
-```ts
- const presets = await db
- .select()
- .from(shiftPresets)
- .where(eq(shiftPresets.calendarId, calendarId))
- .orderBy(asc(shiftPresets.order));
- return NextResponse.json(await withPresetSegments(presets));
-```
-
-- [ ] **Step 2: `POST /api/presets` — validate and persist segments**
-
-Add imports:
-
-```ts
-import { replacePresetSegments } from "@/lib/shift-time-ranges";
-import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
-```
-
-Extend the destructuring:
-
-```ts
- const {
- calendarId,
- title,
- startTime,
- endTime,
- color,
- notes,
- groupName,
- isSecondary,
- isAllDay,
- hideFromStats,
- defaultSignupCapacity,
- segments: requestedSegments,
- } = body;
-```
-
-After the existing calendar fetch and the `createPreset` capability check, before the "max order" block, add:
-
-```ts
- const rawSegments: TimeRange[] = isAllDay || !Array.isArray(requestedSegments)
- ? []
- : requestedSegments;
- if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
- return NextResponse.json(
- { error: "Split shifts are not enabled for this calendar" },
- { status: 400 }
- );
- }
- if (!isAllDay) {
- const validationError = validateTimeRanges(
- toTimeRanges({ startTime, endTime, segments: rawSegments })
- );
- if (validationError) {
- return NextResponse.json({ error: validationError }, { status: 400 });
- }
- }
-```
-
-Replace the insert call:
-
-```ts
- const [preset] = await db
- .insert(shiftPresets)
- .values({
- calendarId,
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color: color || "#3b82f6",
- notes: notes || null,
- groupName: groupName ? trimOrNull(groupName) : null,
- isSecondary: isSecondary || false,
- isAllDay: isAllDay || false,
- hideFromStats: hideFromStats || false,
- defaultSignupCapacity:
- typeof defaultSignupCapacity === "number"
- ? defaultSignupCapacity
- : null,
- order: maxOrder + 1,
- createdBy: user?.id ?? null,
- })
- .returning();
-
- return NextResponse.json(preset);
-```
-
-with:
-
-```ts
- const preset = db.transaction((tx) => {
- const inserted = tx
- .insert(shiftPresets)
- .values({
- calendarId,
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color: color || "#3b82f6",
- notes: notes || null,
- groupName: groupName ? trimOrNull(groupName) : null,
- isSecondary: isSecondary || false,
- isAllDay: isAllDay || false,
- hideFromStats: hideFromStats || false,
- defaultSignupCapacity:
- typeof defaultSignupCapacity === "number"
- ? defaultSignupCapacity
- : null,
- order: maxOrder + 1,
- createdBy: user?.id ?? null,
- })
- .returning()
- .get();
- replacePresetSegments(tx, inserted.id, rawSegments);
- return inserted;
- });
-
- return NextResponse.json({ ...preset, segments: rawSegments });
-```
-
-Add `import { db } from "@/lib/db";` at the top if not already present (it already is — `db` is imported on line 2 of this file).
-
-- [ ] **Step 3: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/presets/route.ts`
-Expected: clean.
-
-- [ ] **Step 4: `PATCH /api/presets/[id]` — validate, persist, and cascade to child shifts**
-
-Add imports to `app/api/presets/[id]/route.ts`:
-
-```ts
-import { replacePresetSegments, replaceShiftSegments, withPresetSegments } from "@/lib/shift-time-ranges";
-import { toTimeRanges, validateTimeRanges, type TimeRange } from "@/lib/time-ranges";
-```
-
-Extend the destructuring in `PATCH`:
-
-```ts
- const {
- title,
- startTime,
- endTime,
- color,
- notes,
- groupName,
- isSecondary,
- isAllDay,
- hideFromStats,
- defaultSignupCapacity,
- segments: requestedSegments,
- } = body;
-```
-
-After the existing permission check (`hasAccess` for `manageOwnPresets`/`manageAnyPresets`) and before the update call, add:
-
-```ts
- const nextIsAllDay = isAllDay !== undefined ? isAllDay : existingPreset.isAllDay;
- let nextSegments: TimeRange[] | undefined;
- if (requestedSegments !== undefined) {
- const rawSegments: TimeRange[] = Array.isArray(requestedSegments) ? requestedSegments : [];
- if (!nextIsAllDay) {
- if (rawSegments.length > 0 && !calendar.splitShiftsEnabled) {
- return NextResponse.json(
- { error: "Split shifts are not enabled for this calendar" },
- { status: 400 }
- );
- }
- const validationError = validateTimeRanges(
- toTimeRanges({
- startTime: startTime ?? existingPreset.startTime,
- endTime: endTime ?? existingPreset.endTime,
- segments: rawSegments,
- })
- );
- if (validationError) {
- return NextResponse.json({ error: validationError }, { status: 400 });
- }
- }
- nextSegments = nextIsAllDay ? [] : rawSegments;
- }
-```
-
-Replace the two existing update calls (preset row + cascaded shifts) with a single transaction that also cascades segments:
-
-```ts
- const updatedPreset = db.transaction((tx) => {
- const updated = tx
- .update(shiftPresets)
- .set({
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color,
- notes: notes || null,
- groupName: normalizedGroupName,
- isSecondary: isSecondary !== undefined ? isSecondary : undefined,
- isAllDay: isAllDay !== undefined ? isAllDay : undefined,
- hideFromStats: hideFromStats !== undefined ? hideFromStats : undefined,
- defaultSignupCapacity:
- defaultSignupCapacity !== undefined
- ? defaultSignupCapacity
- : undefined,
- updatedAt: new Date(),
- })
- .where(eq(shiftPresets.id, id))
- .returning()
- .get();
-
- if (nextSegments !== undefined) {
- replacePresetSegments(tx, id, nextSegments);
- }
-
- // Cascade to every shift created from this preset — title/time/color/
- // notes/isAllDay are already cascaded unconditionally below; segments
- // must follow the same rule so a preset's split-shift edit doesn't
- // silently stop propagating to shifts already created from it.
- const childShifts = tx
- .select({ id: shifts.id })
- .from(shifts)
- .where(
- and(
- eq(shifts.presetId, id),
- eq(shifts.calendarId, existingPreset.calendarId)
- )
- )
- .all();
-
- tx.update(shifts)
- .set({
- title,
- startTime: isAllDay ? "00:00" : startTime,
- endTime: isAllDay ? "23:59" : endTime,
- color,
- notes: notes || null,
- isAllDay: isAllDay !== undefined ? isAllDay : undefined,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(shifts.presetId, id),
- eq(shifts.calendarId, existingPreset.calendarId)
- )
- )
- .run();
-
- if (nextSegments !== undefined) {
- for (const child of childShifts) {
- replaceShiftSegments(tx, child.id, nextSegments);
- }
- }
-
- return updated;
- });
-
- const [withSegments] = await withPresetSegments([updatedPreset]);
- return NextResponse.json(withSegments);
-```
-
-- [ ] **Step 5: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/presets/[id]/route.ts`
-Expected: clean.
-
-- [ ] **Step 6: Manual smoke test**
-
-With the dev server running, create a preset with two ranges, create a shift from it, then PATCH the preset's segments and confirm the shift picks up the new segments:
-```bash
-curl -s -X PATCH http://localhost:3000/api/presets/<presetId> -H "Content-Type: application/json" \
- -d '{"title":"Frühdienst","startTime":"06:00","endTime":"10:00","color":"#3b82f6","segments":[{"startTime":"14:00","endTime":"18:00"}]}' | jq .segments
-curl -s http://localhost:3000/api/shifts/<childShiftId> | jq .segments
-```
-Expected: both print `[{"startTime":"14:00","endTime":"18:00"}]`.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add app/api/presets/route.ts app/api/presets/[id]/route.ts
-git commit -m "feat(api): validate, persist, and cascade preset time segments"
-```
-
----
-
-### Task 6: Calendars API — the `splitShiftsEnabled` toggle
-
-**Files:**
-- Modify: `app/api/calendars/route.ts`
-- Modify: `app/api/calendars/[id]/route.ts`
-
-**Interfaces:**
-- Produces: `GET /api/calendars` rows include `splitShiftsEnabled`; `PATCH /api/calendars/[id]` accepts and persists `splitShiftsEnabled`.
-
-- [ ] **Step 1: Include the field in the calendars list select**
-
-In `app/api/calendars/route.ts`, in the `.select({...})` block, add the field next to `signupsEnabled`:
-
-```ts
- signupsEnabled: calendars.signupsEnabled,
- splitShiftsEnabled: calendars.splitShiftsEnabled,
-```
-
-- [ ] **Step 2: Accept and persist it in the PATCH route**
-
-In `app/api/calendars/[id]/route.ts`, extend the destructuring:
-
-```ts
- const { name, color, guestBundleId, viewSettings, signupsEnabled, splitShiftsEnabled } = body;
-```
-
-Extend `wantsGeneralChange` so the permission gate also covers this field:
-
-```ts
- const wantsGeneralChange =
- name !== undefined ||
- color !== undefined ||
- viewSettings !== undefined ||
- typeof signupsEnabled === "boolean" ||
- typeof splitShiftsEnabled === "boolean";
-```
-
-Add the write, mirroring the `signupsEnabled` block exactly:
-
-```ts
- if (
- typeof splitShiftsEnabled === "boolean" &&
- splitShiftsEnabled !== existingCalendar.splitShiftsEnabled
- ) {
- updateData.splitShiftsEnabled = splitShiftsEnabled;
- changes.push("splitShiftsEnabled");
- }
-```
-
-- [ ] **Step 3: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/calendars/route.ts app/api/calendars/[id]/route.ts`
-Expected: clean.
-
-- [ ] **Step 4: Manual smoke test**
-
-```bash
-curl -s -X PATCH http://localhost:3000/api/calendars/<id> -H "Content-Type: application/json" \
- -d '{"splitShiftsEnabled": true}' | jq .splitShiftsEnabled
-```
-Expected: `true`. Re-run Task 4 Step 8's `curl` against a shift on this same calendar — it should now return `201` instead of `400`.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add app/api/calendars/route.ts "app/api/calendars/[id]/route.ts"
-git commit -m "feat(api): add splitShiftsEnabled calendar toggle"
-```
-
----
-
-### Task 7: Duration and display helpers (incl. stats)
-
-**Files:**
-- Modify: `lib/shift-display.ts`
-- Modify: `app/api/shifts/stats/route.ts`
-
-**Interfaces:**
-- Consumes: `toTimeRanges`, `sumRangeDurations` from `lib/time-ranges.ts`.
-- Produces: `formatTimeRange()` now joins multiple ranges; `getShiftMinutes()` now sums across segments.
-
-- [ ] **Step 1: Update `formatTimeRange` and `getShiftMinutes` in `lib/shift-display.ts`**
-
-Add the import: `import { toTimeRanges, sumRangeDurations } from "@/lib/time-ranges";`
-
-Replace:
-
-```ts
-export function getShiftMinutes(shift: ShiftWithCalendar): number {
- return shift.isAllDay
- ? 0
- : calculateShiftDuration(shift.startTime, shift.endTime);
-}
-```
-
-with:
-
-```ts
-export function getShiftMinutes(shift: ShiftWithCalendar): number {
- return shift.isAllDay ? 0 : sumRangeDurations(toTimeRanges(shift));
-}
-```
-
-Replace:
-
-```ts
-export function formatTimeRange(times: {
- startTime: string;
- endTime: string;
-}): string {
- return `${times.startTime.slice(0, 5)} – ${times.endTime.slice(0, 5)}`;
-}
-```
-
-with:
-
-```ts
-export function formatTimeRange(times: {
- startTime: string;
- endTime: string;
- segments?: { startTime: string; endTime: string }[];
-}): string {
- return toTimeRanges(times)
- .map((range) => `${range.startTime.slice(0, 5)} – ${range.endTime.slice(0, 5)}`)
- .join(", ");
-}
-```
-
-`calculateShiftDuration` is still imported and used elsewhere in this file (e.g. nowhere else currently, so if `tsc`/lint flags it as unused after this change, remove the now-unused import — check with the next step).
-
-- [ ] **Step 2: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint lib/shift-display.ts`
-Expected: clean; if `calculateShiftDuration` is now unused in this file, remove its import.
-
-- [ ] **Step 3: Update the stats route to sum segments**
-
-In `app/api/shifts/stats/route.ts`, add imports:
-
-```ts
-import { withShiftSegments } from "@/lib/shift-time-ranges";
-import { toTimeRanges, sumRangeDurations } from "@/lib/time-ranges";
-```
-
-After the existing `result` query (the `.select({...}).from(shifts)...` call that selects `id, title, date, startTime, endTime, isAllDay`), attach segments:
-
-```ts
- const resultWithSegments = await withShiftSegments(result);
-```
-
-Replace the duration line inside the `result.forEach((shift) => { ... })` loop — change `result.forEach` to `resultWithSegments.forEach`, and replace:
-
-```ts
- const duration = shift.isAllDay
- ? 0
- : calculateShiftDuration(shift.startTime, shift.endTime);
-```
-
-with:
-
-```ts
- const duration = shift.isAllDay ? 0 : sumRangeDurations(toTimeRanges(shift));
-```
-
-Also change the later `const totalShifts = result.length;` to `const totalShifts = resultWithSegments.length;` (same value, just keeping the variable name consistent with the renamed source array — check every other bare `result` reference in this file with `grep -n "\bresult\b" app/api/shifts/stats/route.ts` and rename them all to `resultWithSegments` so nothing silently keeps reading the pre-segments array).
-
-- [ ] **Step 4: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/shifts/stats/route.ts`
-Expected: clean, no leftover references to the old `result` variable name.
-
-- [ ] **Step 5: Manual smoke test**
-
-```bash
-curl -s "http://localhost:3000/api/shifts/stats?calendarId=<id>&period=month" | jq '.totalMinutes, .stats'
-```
-For a calendar with one split shift (`06:00–10:00` + `15:00–21:00` = 240 + 360 = 600 minutes) and nothing else in the period, expect `totalMinutes: 600`.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add lib/shift-display.ts app/api/shifts/stats/route.ts
-git commit -m "feat: sum split-shift durations in display helpers and stats"
-```
-
----
-
-### Task 8: PDF and ICS exports
-
-**Files:**
-- Modify: `app/api/export/pdf/route.ts`
-- Modify: `app/api/export/ics/route.ts`
-
-**Interfaces:**
-- Consumes: `formatTimeRange` (`lib/shift-display.ts`) for PDF; `toTimeRanges` (`lib/time-ranges.ts`) for ICS.
-
-- [ ] **Step 1: PDF — join ranges**
-
-Both `app/api/export/pdf/route.ts` and `app/api/export/ics/route.ts` use `db.query.shifts.findMany(...)` (the Drizzle relational API), so they can request the relation directly instead of a separate helper call. In `app/api/export/pdf/route.ts`, change the shifts query:
-
-```ts
- let allShifts = await db.query.shifts.findMany({
- where: inArray(
- shifts.calendarId,
- accessibleCalendars.map((c) => c.id)
- ),
- orderBy: (shifts, { asc }) => [asc(shifts.date)],
- });
-```
-
-to:
-
-```ts
- let allShifts = await db.query.shifts.findMany({
- where: inArray(
- shifts.calendarId,
- accessibleCalendars.map((c) => c.id)
- ),
- orderBy: (shifts, { asc }) => [asc(shifts.date)],
- with: { segments: true },
- });
-```
-
-Add the import `import { formatTimeRange } from "@/lib/shift-display";` and replace:
-
-```ts
- const timeStr = shift.isAllDay
- ? "—" // Em dash for all-day shifts
- : `${shift.startTime} - ${shift.endTime}`;
-```
-
-with:
-
-```ts
- const timeStr = shift.isAllDay ? "—" : formatTimeRange(shift);
-```
-
-- [ ] **Step 2: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/export/pdf/route.ts`
-Expected: clean.
-
-- [ ] **Step 3: ICS — one VEVENT per range**
-
-In `app/api/export/ics/route.ts`, change the shifts query the same way:
-
-```ts
- const allShifts = await db.query.shifts.findMany({
- where: inArray(
- shifts.calendarId,
- accessibleCalendars.map((c) => c.id)
- ),
- orderBy: (shifts, { asc }) => [asc(shifts.date)],
- with: { segments: true },
- });
-```
-
-Add the import `import { toTimeRanges } from "@/lib/time-ranges";`. Replace the whole `for (const shift of allShifts) { ... }` body's event-creation section — everything from `const vevent = new ICAL.Component("vevent");` through `cal.addSubcomponent(vevent);` — with a loop over ranges that shares the shift's summary/description/color but gives each range its own VEVENT:
-
-```ts
- for (const shift of allShifts) {
- const shiftDate = shift.date as Date;
- const calendarName = calendarMap.get(shift.calendarId);
- const summary = isMultiCalendar
- ? `[${calendarName}] ${shift.title}`
- : shift.title;
-
- const ranges = shift.isAllDay ? [null] : toTimeRanges(shift);
-
- ranges.forEach((range, index) => {
- const vevent = new ICAL.Component("vevent");
- const event = new ICAL.Event(vevent);
-
- event.uid = index === 0 ? shift.id : `${shift.id}-seg-${index}`;
- event.summary = summary;
- if (shift.notes) {
- event.description = shift.notes;
- }
-
- if (!range) {
- // All-day event (DTEND is exclusive per RFC 5545)
- const dateStr = formatDateToLocal(shiftDate);
- event.startDate = ICAL.Time.fromDateString(dateStr);
-
- const endDate = new Date(shiftDate);
- endDate.setDate(endDate.getDate() + 1);
- const endYear = endDate.getFullYear();
- const endMonth = String(endDate.getMonth() + 1).padStart(2, "0");
- const endDay = String(endDate.getDate()).padStart(2, "0");
- event.endDate = ICAL.Time.fromDateString(`${endYear}-${endMonth}-${endDay}`);
- } else {
- const [startHour, startMinute] = range.startTime.split(":").map(Number);
- const [endHour, endMinute] = range.endTime.split(":").map(Number);
-
- const startDateTime = new Date(shiftDate);
- startDateTime.setHours(startHour, startMinute, 0, 0);
-
- const endDateTime = new Date(shiftDate);
- endDateTime.setHours(endHour, endMinute, 0, 0);
-
- if (endDateTime <= startDateTime) {
- endDateTime.setDate(endDateTime.getDate() + 1);
- }
-
- event.startDate = ICAL.Time.fromJSDate(startDateTime, true);
- event.endDate = ICAL.Time.fromJSDate(endDateTime, true);
- }
-
- vevent.addPropertyWithValue("color", shift.color);
- vevent.addPropertyWithValue("x-apple-calendar-color", shift.color);
-
- cal.addSubcomponent(vevent);
- });
- }
-```
-
-- [ ] **Step 4: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint app/api/export/ics/route.ts`
-Expected: clean.
-
-- [ ] **Step 5: Manual smoke test**
-
-```bash
-curl -s -X POST http://localhost:3000/api/export/ics -H "Content-Type: application/json" \
- -d '{"calendarIds":["<id>"]}' -o /tmp/test-export.ics
-grep -c BEGIN:VEVENT /tmp/test-export.ics
-```
-For a calendar with one split shift (2 ranges) and nothing else, expect `2`.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add app/api/export/pdf/route.ts app/api/export/ics/route.ts
-git commit -m "feat(export): render split-shift ranges in PDF and ICS exports"
-```
-
----
-
-### Task 9: Calendar settings UI toggle + its i18n keys
-
-**Files:**
-- Modify: `components/calendar-permissions-panel.tsx`
-- Modify: `messages/de.json`, `messages/en.json`, `messages/es.json`, `messages/fr.json`, `messages/it.json`, `messages/cs.json`
-
-**Interfaces:**
-- Consumes: `useCalendars().updateCalendar` (already handles arbitrary `CalendarUpdateInput` fields), `ToggleRow`/`InfoNote`/`SectionLabel` from `components/form-kit`.
-
-- [ ] **Step 1: Add the i18n keys to `messages/de.json`**
-
-Find the `sharingSheet` object (it already has `signupsEnabledLabel`/`signupsEnabledDesc`) and add, next to those two keys:
-
-```json
- "splitShiftsEnabledLabel": "Geteilte Dienste aktivieren",
- "splitShiftsEnabledDesc": "Erlaubt mehrere Zeitfenster in einer Schicht oder Vorlage, z. B. 06:00–10:00 und 15:00–21:00. Ausgeschaltet werden zusätzliche Zeitfenster überall ausgeblendet.",
-```
-
-Find the `permissionBundles` object (it has `groups.signups`, `signupsLocked`, `signupsCapabilityHint`) and add:
-
-```json
- "splitShiftsLocked": "Nur wer Kalendereinstellungen verwalten darf, kann geteilte Dienste ein- oder ausschalten.",
-```
-
-and inside its nested `groups` object, next to `"signups": "Anmeldungen"`:
-
-```json
- "splitShifts": "Geteilte Dienste",
-```
-
-- [ ] **Step 2: Mirror the same keys into the other 5 locale files**
-
-For each of `en.json`, `es.json`, `fr.json`, `it.json`, `cs.json`, add the same three keys (`sharingSheet.splitShiftsEnabledLabel`, `sharingSheet.splitShiftsEnabledDesc`, `permissionBundles.splitShiftsLocked`, `permissionBundles.groups.splitShifts`) at the same nesting depth, translated. English (`en.json`) reference translation:
-
-```json
- "splitShiftsEnabledLabel": "Enable split shifts",
- "splitShiftsEnabledDesc": "Allows multiple time ranges in one shift or preset, e.g. 06:00–10:00 and 15:00–21:00. Turning this off hides extra time ranges everywhere.",
-```
-```json
- "splitShiftsLocked": "Only someone who can manage calendar settings can turn split shifts on or off.",
-```
-```json
- "splitShifts": "Split shifts",
-```
-
-Translate the same meaning into `es.json`, `fr.json`, `it.json`, `cs.json` following each file's existing tone for the neighboring `signupsEnabled*`/`signupsLocked`/`groups.signups` keys (open each file, find those keys, and match register/formality).
-
-- [ ] **Step 3: Run the i18n check**
-
-Run: `npm run i18n`
-Expected: no missing/unused key errors for the six new keys.
-
-- [ ] **Step 4: Add the toggle UI**
-
-In `components/calendar-permissions-panel.tsx`, add local state next to `optimisticSignupsEnabled`:
-
-```ts
- const [optimisticSplitShiftsEnabled, setOptimisticSplitShiftsEnabled] = useState<boolean | null>(null);
-```
-
-Right after `const signupsEnabled = ...` line, add:
-
-```ts
- const splitShiftsEnabled =
- optimisticSplitShiftsEnabled ?? calendar?.splitShiftsEnabled ?? false;
-```
-
-Right after `handleSignupsEnabledChange`, add the matching handler:
-
-```ts
- const handleSplitShiftsEnabledChange = async (value: boolean) => {
- if (value === splitShiftsEnabled) return;
- setOptimisticSplitShiftsEnabled(value);
- setSaving(true);
- try {
- await updateCalendar(calendarId, { splitShiftsEnabled: value });
- } catch {
- // updateCalendar already reported the error and rolled back the cache.
- } finally {
- setSaving(false);
- setOptimisticSplitShiftsEnabled(null);
- }
- };
-```
-
-Right after the existing signups `<section>` block (the one ending with `</section>` that contains the `signups-enabled` `ToggleRow`), add a second section:
-
-```tsx
- <section className="flex flex-col gap-3 border-t border-line pt-5">
- <SectionLabel className="mb-0">{t("permissionBundles.groups.splitShifts")}</SectionLabel>
- <ToggleRow
- id="split-shifts-enabled"
- title={t("sharingSheet.splitShiftsEnabledLabel")}
- description={t("sharingSheet.splitShiftsEnabledDesc")}
- checked={splitShiftsEnabled}
- onCheckedChange={handleSplitShiftsEnabledChange}
- disabled={saving || !canManageSettings}
- />
- {!canManageSettings && (
- <InfoNote icon={Lock}>{t("permissionBundles.splitShiftsLocked")}</InfoNote>
- )}
- </section>
-```
-
-- [ ] **Step 5: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint components/calendar-permissions-panel.tsx`
-Expected: clean.
-
-- [ ] **Step 6: Manual verification in the browser**
-
-With `npm run dev` running, open the app, go to a calendar's permissions/sharing panel, confirm the new "Geteilte Dienste" section renders below "Anmeldungen" with a working toggle (disabled for non-managers, saving state visible while in flight).
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add components/calendar-permissions-panel.tsx messages/*.json
-git commit -m "feat(ui): add split-shifts calendar toggle"
-```
-
----
-
-### Task 10: Shift form — segment editor
-
-**Files:**
-- Modify: `components/shift-sheet.tsx`
-- Modify: `components/shift-form-fields.tsx`
-- Modify: `hooks/useShiftForm.ts`
-- Modify: `hooks/useShifts.ts`
-- Modify: `messages/de.json`, `messages/en.json`, `messages/es.json`, `messages/fr.json`, `messages/it.json`, `messages/cs.json`
-
-**Interfaces:**
-- Consumes: `TimeRange`, `validateTimeRanges` (`lib/time-ranges.ts`); `useCalendars` for `calendar.splitShiftsEnabled`.
-- Produces: `ShiftFormData.segments: TimeRange[]`.
-
-- [ ] **Step 1: Add the i18n keys**
-
-In `messages/de.json`, add a new top-level `timeRanges` object (place it alphabetically near `shiftSheet`/`shiftSignup`):
-
-```json
- "timeRanges": {
- "add": "Zeitfenster hinzufügen",
- "remove": "Zeitfenster entfernen",
- "errors": {
- "overlap": "Zeitfenster dürfen sich nicht überschneiden.",
- "overnight_segment": "Bei mehreren Zeitfenstern muss jedes am selben Tag enden.",
- "invalid_format": "Ungültige Uhrzeit."
- }
- },
-```
-
-Mirror into the other five locale files, e.g. `en.json`:
-
-```json
- "timeRanges": {
- "add": "Add time range",
- "remove": "Remove time range",
- "errors": {
- "overlap": "Time ranges must not overlap.",
- "overnight_segment": "With multiple time ranges, each one must end on the same day.",
- "invalid_format": "Invalid time."
- }
- },
-```
-
-Translate the same three error keys plus `add`/`remove` into `es.json`, `fr.json`, `it.json`, `cs.json`.
-
-Run: `npm run i18n` — expect no missing-key errors (there will be "unused key" warnings until Step 4 below wires up the actual `t()` calls; that's expected mid-task, resolve by the end of this task).
-
-- [ ] **Step 2: `ShiftFormData` gains `segments`**
-
-In `components/shift-sheet.tsx`, add the field:
-
-```ts
-export interface ShiftFormData {
- date: string;
- startTime: string;
- endTime: string;
- title: string;
- color?: string;
- notes?: string;
- presetId?: string;
- isAllDay?: boolean;
- signupCapacity?: number | null;
- segments?: TimeRange[];
- signupUserIds?: string[];
-}
-```
-
-Add the import `import type { TimeRange } from "@/lib/time-ranges";`.
-
-Update `snapshot()` to include it in the dirty-check:
-
-```ts
-function snapshot(data: ShiftFormData) {
- return JSON.stringify({
- date: data.date,
- startTime: data.startTime,
- endTime: data.endTime,
- title: data.title,
- notes: data.notes || "",
- color: data.color,
- isAllDay: data.isAllDay || false,
- signupCapacity: data.signupCapacity ?? null,
- segments: data.segments ?? [],
- });
-}
-```
-
-Update `initialSnapshot`'s object literal (inside the `useMemo`) to also pass `segments: shift.segments ?? []`.
-
-- [ ] **Step 3: `useShiftForm.ts` manages `segments` in form state**
-
-Add the import `import type { TimeRange } from "@/lib/time-ranges";`. In every place `useState<ShiftFormData>` initializes or `resetForm`/`clearPreset`/`applyPreset` rebuild the object, add `segments: shift?.segments ?? []` (for the initial state and the `open`-effect branch) or `segments: []` (for `resetForm`/`clearPreset`) or `segments: preset.segments ?? []` (for `applyPreset` — the `ShiftPreset` type doesn't carry `segments` by default since it's a joined field, so widen `applyPreset`'s parameter type from `ShiftPreset` to `ShiftPreset & { segments?: TimeRange[] }`).
-
-Concretely:
-- Initial `useState<ShiftFormData>(...)`: add `segments: shift?.segments ?? [],`
-- `applyPreset`: change signature to `(preset: ShiftPreset & { segments?: TimeRange[] })` and add `segments: preset.segments ?? [],` to the `setFormData` call.
-- `clearPreset`: add `segments: [],`
-- `resetForm`: add `segments: [],`
-- The `open`-effect's `newFormData` object: add `segments: shift?.segments ?? [],`, and add `formDataRef.current.segments !== newFormData.segments` is wrong for arrays — instead add a length+content check: extend `needsUpdate` with ``JSON.stringify(formDataRef.current.segments ?? []) !== JSON.stringify(newFormData.segments ?? [])``.
-
-- [ ] **Step 4: `ShiftFormFields` — render the segment editor**
-
-Add imports:
-
-```ts
-import { validateTimeRanges, toTimeRanges, type TimeRange } from "@/lib/time-ranges";
-import { Button } from "@/components/ui/button";
-import { Plus, X } from "lucide-react";
-```
-
-Add a new prop `splitShiftsEnabled?: boolean` to `ShiftFormFieldsProps`.
-
-Right after the existing start/end/duration `<div className="flex gap-2.5">` block (still inside the `<div className="flex flex-col gap-2.5 lg:gap-3">` wrapper, before the `<CheckRow id="allDay" ...>`), add:
-
-```tsx
- {!formData.isAllDay && (formData.segments?.length ?? 0) > 0 && (
- <div className="flex flex-col gap-2">
- {(formData.segments ?? []).map((segment, index) => (
- <div key={index} className="flex items-end gap-2.5">
- <Field label={t("shiftSheet.start")} className="flex-1">
- <Input
- type="time"
- value={segment.startTime}
- onChange={(e) => {
- const next = [...(formData.segments ?? [])];
- next[index] = { ...next[index], startTime: e.target.value };
- onFormDataChange({ ...formData, segments: next });
- }}
- disabled={readOnly}
- className={cn(inputClass, "font-mono")}
- />
- </Field>
- <Field label={t("shiftSheet.end")} className="flex-1">
- <Input
- type="time"
- value={segment.endTime}
- onChange={(e) => {
- const next = [...(formData.segments ?? [])];
- next[index] = { ...next[index], endTime: e.target.value };
- onFormDataChange({ ...formData, segments: next });
- }}
- disabled={readOnly}
- className={cn(inputClass, "font-mono")}
- />
- </Field>
- <Button
- type="button"
- variant="outline"
- size="icon"
- className="mb-[1px] shrink-0"
- aria-label={t("timeRanges.remove")}
- disabled={readOnly}
- onClick={() => {
- const next = (formData.segments ?? []).filter((_, i) => i !== index);
- onFormDataChange({ ...formData, segments: next });
- }}
- >
- <X className="size-4" />
- </Button>
- </div>
- ))}
- </div>
- )}
-
- {!formData.isAllDay && splitShiftsEnabled && !readOnly && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="self-start"
- onClick={() =>
- onFormDataChange({
- ...formData,
- segments: [...(formData.segments ?? []), { startTime: "12:00", endTime: "14:00" }],
- })
- }
- >
- <Plus className="size-4" />
- {t("timeRanges.add")}
- </Button>
- )}
-
- {!formData.isAllDay &&
- (() => {
- const error = validateTimeRanges(toTimeRanges(formData));
- return error ? (
- <p className="text-[13px] text-destructive">{t(`timeRanges.errors.${error}`)}</p>
- ) : null;
- })()}
-```
-
-Check the exact class name this codebase uses for inline validation-error text (grep `text-destructive` or similar across `components/*.tsx` — e.g. `grep -rn "text-destructive\|text-error\|text-danger" components | head -5`) and use that project's existing error-text class instead of guessing, if it differs.
-
-- [ ] **Step 5: Thread `splitShiftsEnabled` from `ShiftSheet`**
-
-In `components/shift-sheet.tsx`, add `import { useCalendars } from "@/hooks/useCalendars";`. Inside the `ShiftSheet` component, after `const permission = useCalendarPermission(calendarId);`, add:
-
-```ts
- const { calendars } = useCalendars();
- const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
-```
-
-Pass it to `<ShiftFormFields ... splitShiftsEnabled={splitShiftsEnabled} />`.
-
-Also update `handleSave`'s `submitData` to pass segments through unchanged for all-day (clear them) shifts:
-
-```ts
- const submitData = {
- ...formData,
- startTime: formData.isAllDay ? "00:00" : formData.startTime,
- endTime: formData.isAllDay ? "23:59" : formData.endTime,
- segments: formData.isAllDay ? [] : formData.segments,
- ...(!shift ? { signupUserIds: pendingSignupUserIds } : {}),
- };
-```
-
-Also block saving on a validation error — change `saveDisabled` on `<BaseSheet>`:
-
-```tsx
- saveDisabled={
- !formData.title.trim() ||
- (shift && !hasChanges()) ||
- (!formData.isAllDay && !!validateTimeRanges(toTimeRanges(formData)))
- }
-```
-(add the same `validateTimeRanges`/`toTimeRanges` import used in Step 4 to this file too).
-
-- [ ] **Step 6: `useShifts.ts` — carry `segments` in the optimistic shift**
-
-Find `createOptimisticShift`-equivalent code inside the `useCreateShift`-style mutation (the block building an optimistic `ShiftWithCalendar` around lines 145-160, referenced by `startTime: formData.startTime, endTime: formData.endTime,`). Add `segments: formData.segments ?? [],` next to those two lines, and do the same in the update mutation's optimistic patch (around lines 255-265).
-
-- [ ] **Step 7: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint components/shift-sheet.tsx components/shift-form-fields.tsx hooks/useShiftForm.ts hooks/useShifts.ts`
-Expected: clean.
-
-- [ ] **Step 8: Run the i18n check again**
-
-Run: `npm run i18n`
-Expected: no missing or unused keys now that `timeRanges.*` is actually referenced from `shift-form-fields.tsx`.
-
-- [ ] **Step 9: Manual browser verification**
-
-With `npm run dev` running and a calendar that has `splitShiftsEnabled: true` (set via the Task 9 UI or a direct `curl` PATCH), open the shift-creation sheet:
-- Confirm the "Add time range" button appears and adds a second start/end row.
-- Enter an overlapping range and confirm the inline error text appears and Save is disabled.
-- Fix the overlap, Save, and confirm the created shift shows both ranges (e.g. via `day-detail.tsx`'s time label).
-- Toggle the calendar's split-shifts setting off and confirm the "Add time range" button disappears from a fresh create sheet (existing split shifts stay visible per the spec's "hidden, not deleted" rule — don't expect them to vanish from the grid, since Task 12 changes only the *display* of the primary+segments label, not a filter).
-
-- [ ] **Step 10: Commit**
-
-```bash
-git add components/shift-sheet.tsx components/shift-form-fields.tsx hooks/useShiftForm.ts hooks/useShifts.ts messages/*.json
-git commit -m "feat(ui): add split-shift time-range editor to the shift form"
-```
-
----
-
-### Task 11: Preset form — segment editor
-
-**Files:**
-- Modify: `components/preset-form.tsx`
-- Modify: `hooks/usePresets.ts`
-- Modify: `hooks/useShiftForm.ts`
-
-**Interfaces:**
-- Consumes: `TimeRange`, `validateTimeRanges` (`lib/time-ranges.ts`).
-- Produces: `PresetFormData.segments: TimeRange[]`.
-
-**Note (added after Task 10's review):** `hooks/useShiftForm.ts`'s `saveAsPresetHandler` (added/touched in Task 10) builds a `PresetFormData` literal for `createPreset(...)` without `segments` — it couldn't set it before this task, since the field didn't exist yet. Once this task makes `segments: TimeRange[]` required on `PresetFormData`, that call site must be updated explicitly to `segments: shiftData.segments ?? []` — the shift's *actual* segments, not an empty default. Saving a split shift as a preset must preserve its segments; silently defaulting to `[]` here would be a data-loss bug, not just a type-safety fix. This is called out explicitly (not left to the generic "grep for other literals" step below) because it's the one site where real data is available and dropping it would be user-visible.
-
-- [ ] **Step 1: `PresetFormData` gains `segments`**
-
-In `hooks/usePresets.ts`, add the import `import type { TimeRange } from "@/lib/time-ranges";` and extend:
-
-```ts
-export interface PresetFormData {
- title: string;
- startTime: string;
- endTime: string;
- color: string;
- notes: string;
- groupName: string;
- isSecondary: boolean;
- isAllDay: boolean;
- hideFromStats: boolean;
- defaultSignupCapacity?: number | null;
- segments: TimeRange[];
-}
-```
-
-Update `createOptimisticPreset` to include `segments: formData.segments,` in its returned object (widen its return type to `ShiftPreset & { segments: TimeRange[] }` since the base `ShiftPreset` type has no `segments` field).
-
-- [ ] **Step 2: `EMPTY_PRESET_FORM`, `presetToFormData`, `samePresetForm` in `components/preset-form.tsx`**
-
-Add the import `import type { TimeRange } from "@/lib/time-ranges";`. Update:
-
-```ts
-export const EMPTY_PRESET_FORM: PresetFormData = {
- title: "",
- startTime: "09:00",
- endTime: "17:00",
- color: DEFAULT_COLOR,
- notes: "",
- groupName: "",
- isSecondary: false,
- isAllDay: false,
- hideFromStats: false,
- defaultSignupCapacity: null,
- segments: [],
-};
-
-export function presetToFormData(preset: ShiftPreset & { segments?: TimeRange[] }): PresetFormData {
- return {
- title: preset.title,
- startTime: preset.startTime,
- endTime: preset.endTime,
- color: preset.color,
- notes: preset.notes || "",
- groupName: preset.groupName || "",
- isSecondary: preset.isSecondary || false,
- isAllDay: preset.isAllDay || false,
- hideFromStats: preset.hideFromStats || false,
- defaultSignupCapacity: preset.defaultSignupCapacity ?? null,
- segments: preset.segments ?? [],
- };
-}
-```
-
-`samePresetForm` already does a generic `Object.keys(a).every((key) => a[key] === b[key])` — a strict `===` on two array values is always `false` even for equal contents, which would make the form perpetually "dirty" once `segments` is non-empty. Change it to:
-
-```ts
-export function samePresetForm(a: PresetFormData, b: PresetFormData): boolean {
- const { segments: segmentsA, ...restA } = a;
- const { segments: segmentsB, ...restB } = b;
- return (
- (Object.keys(restA) as (keyof typeof restA)[]).every((key) => restA[key] === restB[key]) &&
- JSON.stringify(segmentsA) === JSON.stringify(segmentsB)
- );
-}
-```
-
-- [ ] **Step 3: Render the segment editor in `PresetFormCard`**
-
-Add the prop `splitShiftsEnabled?: boolean` to `PresetFormCardProps`. Add imports:
-
-```ts
-import { validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
-import { Button } from "@/components/ui/button";
-import { Plus, X } from "lucide-react";
-```
-
-Right after the existing `{!value.isAllDay && (<div className="grid grid-cols-2 gap-2.5">...</div>)}` start/end block, add:
-
-```tsx
- {!value.isAllDay && value.segments.length > 0 && (
- <div className="flex flex-col gap-2">
- {value.segments.map((segment, index) => (
- <div key={index} className="grid grid-cols-[1fr_1fr_auto] items-end gap-2.5">
- <Field label={t("presetSheet.start")}>
- <Input
- type="time"
- value={segment.startTime}
- onChange={(e) => {
- const next = [...value.segments];
- next[index] = { ...next[index], startTime: e.target.value };
- onChange({ segments: next });
- }}
- className={cn(fieldClass, "font-mono")}
- disabled={disabled}
- />
- </Field>
- <Field label={t("presetSheet.end")}>
- <Input
- type="time"
- value={segment.endTime}
- onChange={(e) => {
- const next = [...value.segments];
- next[index] = { ...next[index], endTime: e.target.value };
- onChange({ segments: next });
- }}
- className={cn(fieldClass, "font-mono")}
- disabled={disabled}
- />
- </Field>
- <Button
- type="button"
- variant="outline"
- size="icon"
- aria-label={t("timeRanges.remove")}
- disabled={disabled}
- onClick={() => onChange({ segments: value.segments.filter((_, i) => i !== index) })}
- >
- <X className="size-4" />
- </Button>
- </div>
- ))}
- </div>
- )}
-
- {!value.isAllDay && splitShiftsEnabled && !disabled && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="self-start"
- onClick={() =>
- onChange({ segments: [...value.segments, { startTime: "12:00", endTime: "14:00" }] })
- }
- >
- <Plus className="size-4" />
- {t("timeRanges.add")}
- </Button>
- )}
-
- {!value.isAllDay &&
- (() => {
- const error = validateTimeRanges(toTimeRanges(value));
- return error ? <p className="text-[13px] text-destructive">{t(`timeRanges.errors.${error}`)}</p> : null;
- })()}
-```
-
-- [ ] **Step 4: Thread `splitShiftsEnabled` and prevent saving on validation error**
-
-`components/preset-manage-sheet.tsx` renders `<PresetFormCard>` (around line 225) and already has `calendarId` as a prop. Add the import `import { useCalendars } from "@/hooks/useCalendars";` and `import { validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";`, then inside the `PresetsPanel` component add:
-
-```ts
- const { calendars } = useCalendars();
- const splitShiftsEnabled = calendars.find((c) => c.id === calendarId)?.splitShiftsEnabled ?? false;
-```
-
-Pass it to the card: `<PresetFormCard ... splitShiftsEnabled={splitShiftsEnabled} />`.
-
-Extend the existing `canSave` line:
-
-```ts
- const canSave =
- !isSaving &&
- formData.title.trim() !== "" &&
- (!editingPreset || isDirty) &&
- (formData.isAllDay || !validateTimeRanges(toTimeRanges(formData)));
-```
-
-- [ ] **Step 5: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint components/preset-form.tsx hooks/usePresets.ts hooks/useShiftForm.ts`
-Expected: clean once `hooks/useShiftForm.ts`'s `saveAsPresetHandler` sets `segments: shiftData.segments ?? []` (see the note at the top of this task — use the shift's real segments there, not an empty default). Also grep for any other direct `PresetFormData` literal construction that would now be missing the required `segments` field: `grep -rn "PresetFormData = {" components hooks` and `grep -rn ": PresetFormData\b" components hooks` — for any other site found this way (unlike `saveAsPresetHandler`, which has real data available), add `segments: []` since there is no better default.
-
-- [ ] **Step 6: Manual browser verification**
-
-With split shifts enabled on the test calendar, open the preset management sheet, create a preset with two time ranges, save it, confirm it round-trips (reopen and see both ranges). Then create a shift by stamping that preset and confirm the shift got both ranges.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add components/preset-form.tsx hooks/usePresets.ts components/preset-manage-sheet.tsx
-git commit -m "feat(ui): add split-shift time-range editor to the preset form"
-```
-
----
-
-### Task 12: Month grid display
-
-**Files:**
-- Modify: `components/month-grid.tsx`
-
-**Interfaces:**
-- Consumes: `formatTimeRange` (`lib/shift-display.ts`).
-
-- [ ] **Step 1: Use the joined range label in the desktop chip**
-
-Add the import `import { formatTimeRange } from "@/lib/shift-display";` (if not already imported — check the top of the file first). Replace the `time()` helper:
-
-```ts
- const time = (shift: ShiftWithCalendar) => (
- <span className="shrink-0 font-mono text-[10.5px] leading-4 opacity-75">
- {shift.isAllDay ? t("calendarView.allDayShort") : shift.startTime.slice(0, 5)}
- </span>
- );
-```
-
-with:
-
-```ts
- const time = (shift: ShiftWithCalendar) => (
- <span className="shrink-0 whitespace-nowrap font-mono text-[10.5px] leading-4 opacity-75">
- {shift.isAllDay ? t("calendarView.allDayShort") : formatTimeRange(shift)}
- </span>
- );
-```
-
-(`whitespace-nowrap` added because the label can now be longer than a single `HH:MM`; the parent chip is already `flex` with `min-w-0`/`truncate` on the title span, so the row itself will just take the width it needs without wrapping oddly — verify visually in Step 3.)
-
-- [ ] **Step 2: Type-check and lint**
-
-Run: `npx tsc --noEmit && npx eslint components/month-grid.tsx`
-Expected: clean.
-
-- [ ] **Step 3: Manual browser verification**
-
-With a split shift visible in the month grid on desktop, confirm the chip shows `06:00 – 10:00, 15:00 – 21:00 · <title>` and doesn't visually break the row. Resize to a narrow desktop width and confirm it still truncates gracefully (the title truncates via its own `truncate` class; the time span itself doesn't need to shrink further since chips already wrap to their content). Then switch to a phone-width viewport and confirm the phone chip is unaffected (still shows only the title, no time) — per the spec, no phone-specific change is expected or needed here.
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add components/month-grid.tsx
-git commit -m "feat(ui): show split-shift ranges in the desktop month grid"
-```
-
----
-
-### Task 13: Full verification and PR
-
-**Files:** none (verification only, plus opening the PR).
-
-- [ ] **Step 1: Full type check**
-
-Run: `npx tsc --noEmit`
-Expected: zero errors across the whole project.
-
-- [ ] **Step 2: Full test pipeline**
-
-Run: `npm test`
-Expected: lint, build, and i18n all pass. If the build fails on a client component pulling in `better-sqlite3` (the exact failure mode the client/server split in Task 2/3 was meant to avoid), find which client file imports `lib/shift-time-ranges.ts` (it must only ever be imported from `app/api/**` route files) and fix the import to point at `lib/time-ranges.ts` instead.
-
-- [ ] **Step 3: Migration sanity check on a clean database**
-
-```bash
-rm -f data/sqlite.db
-npm run db:migrate
-```
-Expected: exits 0, `data/sqlite.db` is recreated with all tables including `shift_time_segments`, `preset_time_segments`, and `calendars.split_shifts_enabled`. (This only matters for a scratch/dev database — never run this against a database with real data you want to keep.)
-
-- [ ] **Step 4: End-to-end browser walkthrough**
-
-With `npm run dev` running:
-1. Log in (or use `AUTH_ENABLED=false`), create a fresh calendar.
-2. Open its permissions panel, turn on "Geteilte Dienste".
-3. Create a shift with two time ranges (`06:00–10:00`, `15:00–21:00`); confirm it saves and displays both ranges in the month grid and in the day-detail sheet.
-4. Create a preset with two ranges, stamp it onto a day, confirm the resulting shift has both ranges.
-5. Edit the preset's ranges; confirm the previously stamped shift's ranges update too (the cascade from Task 5).
-6. Export that month as PDF and as ICS; open both and confirm the split shift shows both ranges (PDF: one joined line; ICS: two separate events).
-7. Turn "Geteilte Dienste" back off; confirm the "Add time range" button disappears from the create-shift sheet, per the spec's "hidden everywhere, not deleted" rule for the calendar-level toggle.
-8. Create a normal (non-split) shift on an unrelated, already-existing calendar and confirm nothing about its appearance or behavior changed.
-
-- [ ] **Step 5: Push the branch and open the PR**
-
-```bash
-git push -u origin feat/split-shifts
-gh pr create --title "feat: support split shifts with multiple time ranges" --body "$(cat <<'EOF'
-## Summary
-- Shifts and presets can now hold multiple, non-contiguous time ranges on the same day (e.g. 06:00–10:00 and 15:00–21:00), gated per calendar behind a new owner/admin toggle (`splitShiftsEnabled`), off by default.
-- Additional ranges live in two new child tables (`shiftTimeSegments`, `presetTimeSegments`); the primary range stays on the existing `startTime`/`endTime` columns for full backward compatibility.
-- PDF export joins all ranges into one line; ICS export emits one VEVENT per range.
-
-Closes #191.
-
-## Test plan
-- [ ] `npm test` passes (lint, build, i18n)
-- [ ] Create/edit a split shift and a split preset in the browser; verify validation (overlap, chronological order) and the calendar-level toggle
-- [ ] Verify a preset's segment edits cascade to shifts already created from it
-- [ ] Verify PDF and ICS exports for a split shift
-- [ ] Verify existing (non-split) shifts/calendars are visually and functionally unchanged
-EOF
-)"
-```
-
-Expected: PR created; report the URL back.
diff --git a/docs/superpowers/plans/2026-09-17-calendar-view-modes.md b/docs/superpowers/plans/2026-09-17-calendar-view-modes.md
deleted file mode 100644
index 2a65632..0000000
--- a/docs/superpowers/plans/2026-09-17-calendar-view-modes.md
+++ /dev/null
@@ -1,1921 +0,0 @@
-# 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-15-split-shifts-design.md b/docs/superpowers/specs/2026-09-15-split-shifts-design.md
deleted file mode 100644
index afd7144..0000000
--- a/docs/superpowers/specs/2026-09-15-split-shifts-design.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# Split Shifts — Design
-
-Source: [GitHub issue #191](https://github.com/panteLx/BetterShift/issues/191). Common in German elder care ("Altenpflege"): a single duty made of two or more non-contiguous time ranges on the same day, e.g. `06:00–10:00` and `15:00–21:00`.
-
-## Goals
-
-- A shift (and a preset) can have one or more time ranges on the same calendar day, not just one.
-- Backward compatible: the vast majority of shifts stay single-range and every existing code path that reads `shift.startTime`/`shift.endTime` keeps working unmodified.
-- Opt-in per calendar, owner/admin controlled, off by default.
-
-## Non-goals
-
-- A time range spanning midnight *within* a split shift (multi-range wraparound). A single-range shift crossing midnight is already supported today and is untouched.
-- Per-range signups. A signup still applies to the whole shift.
-- A generic multi-range concept for anything other than shifts/presets (e.g. notes, external events).
-
-## Data model
-
-Two new child tables, following the existing `shiftSignups` one-to-many-on-parent-id pattern rather than a JSON column (no JSON-blob precedent exists for arbitrary per-row data in this schema; the closest JSON columns, `calendars.viewSettings` and `calendarPermissionBundles.capabilities`, are fixed-shape and code-typed, not applicable here):
-
-```ts
-export const shiftTimeSegments = sqliteTable(
- "shift_time_segments",
- {
- id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
- shiftId: text("shift_id").notNull().references(() => shifts.id, { onDelete: "cascade" }),
- startTime: text("start_time").notNull(),
- endTime: text("end_time").notNull(),
- createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
- },
- (table) => [index("shift_time_segments_shiftId_idx").on(table.shiftId)]
-);
-
-export const presetTimeSegments = sqliteTable(
- "preset_time_segments",
- {
- id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
- presetId: text("preset_id").notNull().references(() => shiftPresets.id, { onDelete: "cascade" }),
- startTime: text("start_time").notNull(),
- endTime: text("end_time").notNull(),
- createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),
- },
- (table) => [index("preset_time_segments_presetId_idx").on(table.presetId)]
-);
-```
-
-- These tables hold **only the additional ranges** (segment 2, 3, …). The first/primary range stays on `shifts.startTime`/`endTime` and `shiftPresets.startTime`/`endTime` exactly as today.
-- No `order` column: write-time validation enforces chronological order, read-time code sorts by `startTime` if it ever needs to (in practice segments are already stored in order).
-- Relations added to `shiftsRelations`/`shiftPresetsRelations` (`many(shiftTimeSegments)` / `many(presetTimeSegments)`).
-
-New column:
-
-```ts
-// calendars table
-splitShiftsEnabled: integer("split_shifts_enabled", { mode: "boolean" }).notNull().default(false),
-```
-
-Modeled exactly after `signupsEnabled` ("master switch... Owner/admin only"): a calendar-wide feature flag, not a permission-bundle capability. Off hides the extra segments everywhere (same behavior contract as `signupsEnabled`), not just in the create form — if a calendar's owner turns it off after split shifts already exist, those shifts fall back to showing/using only their primary range until the owner turns it back on. Data in `shiftTimeSegments` is not deleted when the flag is turned off.
-
-No data migration needed beyond the schema migration itself — existing shifts/presets are untouched (no rows in the new tables, flag defaults `false`).
-
-## Validation
-
-Applied both client-side (immediate form feedback) and server-side (routes have no centralized Zod layer today; validation stays inline like the rest of `app/api/shifts/**` and `app/api/presets/**`):
-
-- All ranges (primary + segments) must be non-overlapping and in chronological order, compared as same-day minute-of-day values (no midnight wraparound across ranges — see Non-goals).
-- The server additionally rejects a write with more than one range when `calendars.splitShiftsEnabled` is `false` for the target calendar — the flag is enforced, not just hidden in the UI.
-
-## API contract
-
-Request and response bodies for `/api/shifts`, `/api/shifts/[id]`, `/api/presets`, `/api/presets/[id]` keep `startTime`/`endTime` exactly as they are today (the primary range) and gain one new, optional, additive field: `segments: { startTime: string; endTime: string }[]` — the *additional* ranges only (empty/omitted for a normal shift). This is deliberately not a unified `timeRanges` array that replaces `startTime`/`endTime`: keeping the primary pair as its own top-level fields means every existing reader (grid, exports, sync, stats) needs zero changes to keep working, and the shift/preset form only needs new markup for the extra rows — the existing start/end inputs are untouched.
-
-A shared helper `toTimeRanges({ startTime, endTime, segments })` reassembles the full ordered list `[primary, ...segments]` wherever validation, duration, or display code needs to look at all ranges together. This logic is split across two new files by where it can run:
-
-- `lib/time-ranges.ts` — pure, client-safe (no `db` import, so it can be used from form components): `TimeRange` type, `toTimeRanges()`, `validateTimeRanges()` (returns an error code or `null`), `sumRangeDurations()`.
-- `lib/shift-time-ranges.ts` — server-only (imports `db`): `replaceShiftSegments()`, `replacePresetSegments()` (delete-then-insert into the child table, same transaction as the parent row write), `withShiftSegments()`, `withPresetSegments()` (attach a `segments` array to a list of rows, following the existing `withSignups()` pattern in `lib/shift-signups.ts`).
-
-This split matters: `lib/shift-display.ts` and the shift/preset form components are used client-side, and importing anything that pulls in `better-sqlite3` there would break the client bundle. On write, the route validates the full range list via `toTimeRanges()` + `validateTimeRanges()`, rejects if `segments.length > 0` while the calendar's `splitShiftsEnabled` is `false`, and persists via `replaceShiftSegments()`/`replacePresetSegments()`.
-
-`PATCH /api/presets/[id]` already cascades `title`/`startTime`/`endTime`/`color`/`notes`/`isAllDay` from the preset onto every shift created from it (unconditional overwrite, not just on first creation). This must be extended to also cascade `segments` the same way — otherwise a preset's split-shift edit would silently stop propagating to its already-created shifts, unlike every other field.
-
-## Frontend
-
-- `hooks/useShiftForm.ts` / `hooks/usePresets.ts`'s form data hold `startTime`/`endTime` exactly as today plus a new `segments: TimeRange[]` array (additional ranges only, mirroring the API contract). Preset→shift copy logic (`applyPreset`) copies `preset.segments` into the new shift's `segments`.
-- `components/shift-form-fields.tsx` / `components/preset-form.tsx`: the existing start/end row is untouched; additional rows are rendered by mapping over `segments`, each with its own start/end pickers and a remove ("×") action. An "add range" action appears only when `calendar.splitShiftsEnabled`.
-- `hooks/useDirtyState` comparison (the `snapshot()` function in `shift-sheet.tsx`, `samePresetForm()` for presets) is extended to include `segments` in the compared value.
-- `lib/shift-display.ts`:
- - `formatTimeRange()` extended to accept an optional `segments` field and join multiple ranges via `toTimeRanges()` (`"06:00–10:00, 15:00–21:00"`). Consumed as-is by `day-detail.tsx` and `shift-sheet.tsx` — both already funnel through this one shared, responsive component for desktop and phone, so no separate mobile treatment is needed (confirmed by inspection: the phone month-grid chips display no time at all today, only the shift title, so they are unaffected either way).
- - `getShiftMinutes()` uses `toTimeRanges()` + `sumRangeDurations()` (from `lib/time-ranges.ts`) instead of a single `calculateShiftDuration()` call. `app/api/shifts/stats/route.ts` does its own manual `.select()` (not the shared helper), so it separately fetches each result shift's segments and does the same `toTimeRanges()` + `sumRangeDurations()` call in place of its current single-pair `calculateShiftDuration()`.
-- `components/month-grid.tsx` desktop chip: shows the combined `formatTimeRange()` label instead of just `startTime`. Phone chip: unchanged (no time shown there today).
-- `sortShifts` (`lib/shift-display.ts`) keeps sorting by `startTime` — validation guarantees that's the earliest range, so no change in meaning.
-
-## Exports & sync
-
-- **PDF** (`app/api/export/pdf/route.ts`): use the same joined range string instead of the current single `startTime`–`endTime` interpolation.
-- **ICS** (`app/api/export/ics/route.ts`): a split shift becomes multiple VEVENTs — one per range, same `SUMMARY`/`DESCRIPTION`, `UID` of `"<shiftId>"` for the primary range and `"<shiftId>-seg-<n>"` for each additional one, each with its own `DTSTART`/`DTEND`.
-- **External sync** (`lib/external-calendar-utils.ts`, the sync route): unaffected. Incoming events always produce single-range shifts; `shiftTimeSegments` is never populated by sync, so the fingerprint/`needsUpdate` diff logic needs no changes.
-
-## Calendar settings UI
-
-- New toggle in `components/calendar-permissions-panel.tsx`, next to the existing `signupsEnabled` toggle, backed by `splitShiftsEnabled` on the same `PATCH /api/calendars/[id]` route, gated by the same `manageCalendarSettings` capability check already used for that route.
-
-## i18n
-
-New keys (added to `messages/de.json` first, then mirrored to `en`/`es`/`fr`/`it`/`cs` per the project's i18n workflow): add/remove time range labels, the calendar-settings toggle label + description, and the two validation error messages (overlap, chronological order).
-
-## Testing
-
-No unit-test framework in this repo — verification is the standard `npm test` pipeline (lint + build + i18n) plus manual exercising of the feature in the running app (create/edit a split shift and a split preset, toggle the calendar setting off and confirm segments disappear, check PDF and ICS export output, confirm a non-split calendar and non-split shifts are pixel-for-pixel unaffected).
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
deleted file mode 100644
index ce407bb..0000000
--- a/docs/superpowers/specs/2026-09-17-calendar-view-modes-design.md
+++ /dev/null
@@ -1,163 +0,0 @@
-# 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/docs/superpowers/specs/2026-09-18-custom-fields-design.md b/docs/superpowers/specs/2026-09-18-custom-fields-design.md
deleted file mode 100644
index 015f580..0000000
--- a/docs/superpowers/specs/2026-09-18-custom-fields-design.md
+++ /dev/null
@@ -1,279 +0,0 @@
-# Custom Fields for Shifts and Presets — Design
-
-Source: GitHub issue [#141](https://github.com/panteLx/BetterShift/issues/141). Shifts and presets carry a fixed set of columns; a team that needs one more piece of information per shift — the on-call phone number in the reporter's case — has no place to put it and currently has to patch `lib/db/schema.ts` plus a dozen call sites by hand.
-
-## Goals
-
-- A calendar owner can define extra, typed fields on their calendar without touching code.
-- Shifts and presets carry values for those fields; a preset's value pre-fills a shift created from it.
-- Values travel with the shift/preset in the existing API responses, so an API consumer reads `shift.customFields.phone` without a second request.
-- Values appear in the shift and preset forms, in the day detail column, in the month and week cells (opt-in), and in the PDF and ICS exports.
-
-## Non-goals
-
-- No instance-wide field catalog. See "Deviation from the issue" below.
-- No filtering, grouping or statistics by field value — a follow-up issue.
-- No multi-select, textarea, file upload or rich text. Five scalar types only.
-- No field values in compare mode.
-- No per-user view setting for hiding the values in the month/week grid. `lib/view-settings.ts` is untouched; see "No view setting".
-- No changing a field's type after creation.
-- External sync is not extended: synced shifts are read-only, and their field values are too.
-
-## Deviation from the issue
-
-The reporter asked for **global, admin-managed** definitions. This design makes them **per calendar, managed via a permission bundle capability** instead.
-
-Everything in BetterShift hangs off `calendarId`. An instance-wide field would appear in every calendar of every user, which is right for a single-tenant company install and wrong for a shared instance hosting unrelated calendars. Per-calendar definitions give the reporter's case the same result — they own their calendars, so they define the fields — without imposing the catalog on strangers. The restriction they asked for ("only developers, not users") is expressed as a capability that is off by default in every bundle seed except `admin`, and is guest-ineligible.
-
-## Decisions taken with the maintainer
-
-| Question | Decision |
-|---|---|
-| Scope of definitions | Per calendar, managed by owner / `manageCustomFields` |
-| Preset → shift | Preset value is a default, copied into the shift on creation (like `defaultSignupCapacity`); no live inheritance |
-| Types | `text`, `number`, `date`, `checkbox`, `select` |
-| Permission for setting values | None extra — whoever may edit the shift/preset may set its values |
-| Value storage | Two parallel child tables, mirroring `shift_time_segments` / `preset_time_segments` |
-| Surfaces | Shift form, preset form, day detail column, month/week cells, PDF, ICS |
-| Month/week visibility | `showInCalendar` on the definition only; no per-user view setting |
-
-### Why two child tables
-
-Three options were weighed:
-
-- **JSON column on `shifts` and `shift_presets`** — no join, fewest files touched, but deleting a definition orphans its values in every row, and cleaning up means rewriting every shift.
-- **One EAV table for both entities** — `entityId` would point at two different tables, so it cannot carry a foreign key and cannot cascade; deleting a shift would leave its values behind for the application to clean up.
-- **Two parallel child tables (chosen)** — `ON DELETE CASCADE` from both sides, and the read path already knows how to group child rows onto shifts because `lib/shift-time-ranges.ts` does exactly that for time segments. Cost: one more table and two near-identical query helpers.
-
-## Data model
-
-Three new tables in `lib/db/schema.ts`.
-
-```ts
-export const calendarCustomFields = sqliteTable("calendar_custom_fields", {
- id, // uuid
- calendarId, // → calendars.id, cascade
- key, // stable slug, unique per calendar, immutable after creation
- label, // display name, freely renameable
- type, // "text" | "number" | "date" | "checkbox" | "select"
- options, // json {id,label}[] — only for type "select", else null
- required, // boolean, default false
- showInCalendar, // boolean, default false — see "Surfaces"
- order, // integer, default 0
- createdBy, // → user.id, set null
- createdAt, updatedAt,
-});
-// unique(calendarId, key), index(calendarId)
-
-export const shiftCustomFieldValues = sqliteTable("shift_custom_field_values", {
- id,
- shiftId, // → shifts.id, cascade
- fieldId, // → calendarCustomFields.id, cascade
- value, // text, serialized per the definition's type
-});
-// unique(shiftId, fieldId), index(shiftId)
-
-export const presetCustomFieldValues = sqliteTable("preset_custom_field_values", {
- id,
- presetId, // → shiftPresets.id, cascade
- fieldId, // → calendarCustomFields.id, cascade
- value, // text
-});
-// unique(presetId, fieldId), index(presetId)
-```
-
-`key` is deliberately separate from `label`. The API contract is `shift.customFields.<key>`; a label someone renames must not break a consumer. `key` is lowercase, `[a-z0-9_]`, unique per calendar, and cannot be changed once the field exists.
-
-Values are a single `TEXT` column in every case, serialized per type:
-
-| Type | Stored as |
-|---|---|
-| `text` | the string, trimmed |
-| `number` | decimal string, `Number.isFinite` guaranteed on write |
-| `date` | local `YYYY-MM-DD` via `formatDateToLocal()` — never through a UTC conversion |
-| `checkbox` | `"true"` / `"false"` |
-| `select` | the option's `id` |
-
-Migration via `npm run db:generate` + `npm run db:migrate`; the generated SQL, snapshot and journal entry are committed together.
-
-## Shared logic: `lib/custom-fields.ts`
-
-Modelled on `lib/view-settings.ts` — one module that routes and client both import.
-
-```ts
-export const CUSTOM_FIELD_TYPES = ["text", "number", "date", "checkbox", "select"] as const;
-export type CustomFieldType = (typeof CUSTOM_FIELD_TYPES)[number];
-
-export interface CustomFieldDefinition { /* the row shape, options typed */ }
-export interface CustomFieldOption { id: string; label: string; }
-
-export function serializeValue(type, input): string | null;
-export function parseValue(type, raw): string | number | boolean | null;
-export function validateFieldValue(definition, raw): { ok: true } | { ok: false; error: string };
-export function sanitizeDefinition(input): CustomFieldDefinition | null;
-export function normalizeKey(input): string | null;
-```
-
-Rules enforced server-side regardless of what the client sent:
-
-- A `required` field rejects an empty value on write.
-- A `number` that does not parse is rejected.
-- A `select` value that is not one of the definition's option ids is rejected.
-- `options` is accepted only for `type: "select"`, and must be a non-empty array of `{id, label}` with unique ids.
-- An unknown key in an incoming `customFields` object is **dropped silently, not rejected** — a client holding a stale catalog must still be able to save a shift.
-
-## Permissions
-
-New capability `manageCustomFields` in `lib/permission-bundles.ts`:
-
-- Added to `CAPABILITIES` and to the `administration` group in `CAPABILITY_GROUPS`.
-- Guest-ineligible (added to `GUEST_INELIGIBLE`), like `manageCalendarSettings` — a share link must not let someone rebuild a foreign calendar's catalog.
-- Present in the `admin` bundle seed only. `read`, `contribute` and `manage` seeds do not gain it, so existing bundles do not silently widen on upgrade.
-- No `CAPABILITY_DEPENDENCIES` entry; it stands alone.
-
-Setting values needs no capability of its own. The value belongs to the shift or preset, so `editOwnShift` / `editAnyShift` and `manageOwnPresets` / `manageAnyPresets` already gate it.
-
-With `AUTH_ENABLED=false` every calendar resolves to `owner`, so the catalog is editable by anyone — consistent with the rest of the app, and handled by `resolveCalendarAccess()` without a special case.
-
-New i18n keys for the capability's label and description in all six locales, added to `messages/de.json` first.
-
-## API
-
-### Catalog routes
-
-Built like `app/api/calendars/[id]/bundles`:
-
-| Route | Method | Capability |
-|---|---|---|
-| `/api/calendars/[id]/custom-fields` | GET | `viewShifts` |
-| `/api/calendars/[id]/custom-fields` | POST | `manageCustomFields` |
-| `/api/calendars/[id]/custom-fields/[fieldId]` | PATCH | `manageCustomFields` |
-| `/api/calendars/[id]/custom-fields/[fieldId]` | DELETE | `manageCustomFields` |
-| `/api/calendars/[id]/custom-fields/reorder` | PATCH | `manageCustomFields` |
-
-`GET` requires only `viewShifts`: a read-only user still needs the catalog to label the values they can see.
-
-`PATCH` on a field accepts `label`, `options`, `required`, `showInCalendar` — not `key` and not `type`.
-
-Write routes call `rateLimit(request, userId, "customFields")`, with a new entry in the `config` object of `lib/rate-limiter.ts` and a matching env override documented in `.env.example`.
-
-### Values on existing routes
-
-Values get no endpoints of their own. They ride along on the routes that already exist:
-
-- `GET /api/shifts` and `GET /api/presets` return `customFields: Record<key, value>` per row, parsed to the type's JS representation.
-- `POST` / `PATCH` on `/api/shifts`, `/api/shifts/[id]`, `/api/presets`, `/api/presets/[id]` accept the same shape in the body.
-
-`POST /api/shifts` with a `presetId` copies the preset's values into the new shift, at the same place `defaultSignupCapacity` is copied today. An explicit `customFields` object in the request wins over the preset's defaults.
-
-A shift with `syncedFromExternal` rejects any `customFields` in a write, as it rejects other edits.
-
-### `lib/shift-custom-fields.ts`
-
-Copies the shape of `lib/shift-time-ranges.ts` exactly:
-
-```ts
-export function replaceShiftCustomFieldValues(tx, shiftId, values): void;
-export function replacePresetCustomFieldValues(tx, presetId, values): void;
-export async function withShiftCustomFields<T extends { id: string }>(rows, definitions): Promise<...>;
-export async function withPresetCustomFields<T extends { id: string }>(rows, definitions): Promise<...>;
-```
-
-The `with*` helpers take the calendar's definitions so they can key the result by `key` and parse by `type`, and fetch all child rows with a single `inArray` query — no N+1. The `replace*` helpers are delete-then-insert inside the caller's existing transaction.
-
-## Client data layer
-
-`lib/query-keys.ts` gains:
-
-```ts
-customFields: {
- byCalendar: (calendarId: string) => ["custom-fields", calendarId] as const,
-},
-```
-
-Values need no key of their own; they are part of the shift and preset payloads and are invalidated with them.
-
-New `hooks/useCustomFields.ts` (read) and `hooks/useCustomFieldActions.ts` (mutations), following the `onMutate` → `onError` → `onSettled` shape of `hooks/useShifts.ts`. Every catalog mutation additionally invalidates `queryKeys.shifts.byCalendar` and `queryKeys.presets.byCalendar`, because deleting a definition cascades its values away.
-
-Rate-limit responses are handled client-side with `isRateLimitError()` / `handleRateLimitError()`.
-
-## Surfaces
-
-One lever: **`showInCalendar` on the definition**, set by whoever manages the catalog — is this field compact enough to render in a cell at all? There is no per-user toggle; see "No view setting" below.
-
-| Surface | Behaviour |
-|---|---|
-| `components/shift-form-fields.tsx` | All fields, ordered by `order`, below the notes field. One renderer per type from `components/ui/`: Input, Input `type="number"`, the existing date picker, Switch, Select. Read-only for `syncedFromExternal` shifts. |
-| `components/preset-form.tsx` | Same fields, labelled as default values. |
-| `components/day-detail.tsx` | Fields with `showInCalendar` and a non-empty value, rendered under the note (currently `day-detail.tsx:156`), in the same muted typography. |
-| `components/mobile-day-sheet.tsx` | Same as day detail. |
-| `components/month-grid.tsx`, `components/week-grid.tsx` | Fields with `showInCalendar` and a non-empty value. See the height constraint below. |
-| **new** `components/custom-field-manage-sheet.tsx` | The catalog editor, composed from `components/ui/base-sheet.tsx`, registered in `components/dialog-manager.tsx` rather than rendered inline. Form logic lives in `hooks/useCustomFieldForm.ts`. |
-
-Empty values are never rendered on any compact surface.
-
-### Month/week height constraint
-
-`components/month-grid.tsx:248` computes row height as `DESKTOP_ROW + (showShiftNotes && entry.shift.notes ? DESKTOP_SUB_LINE : 0)` — exactly one extra line. Several fields would break that arithmetic and overflow the cell.
-
-Therefore the month and week cells render the visible fields **joined into a single line**, `Label: value · Label: value`, truncated at the end. The height calculation gains the same single `DESKTOP_SUB_LINE`, conditional on the shift having at least one visible non-empty value. The full list stays in the day detail column and the edit sheet.
-
-### No view setting
-
-An earlier draft added `showShiftCustomFields` to `CalendarViewSettings`, mirroring `showShiftNotes`, so a viewer could hide the extra line. It was dropped.
-
-Notes exist in every calendar, so their toggle earns its place in the view settings sheet. Custom fields will exist in almost none — the checkbox would sit in every user's settings for a feature they have not enabled, which is how a settings panel becomes unusable. `showInCalendar` on the definition already keeps noisy fields out of the cells, and the person who defines a field is the person who knows whether it belongs there.
-
-This is cheap to revisit: `sanitizeCalendarViewSettings` falls back per key, so a `showShiftCustomFields` added later reads absent stored settings as the default. No migration, no data format is foreclosed. If viewers of a shared calendar ask for the escape hatch, it is a small follow-up commit.
-
-`lib/view-settings.ts`, `hooks/useViewSettings.ts`, `components/view-settings-sheet.tsx`, `app/page.tsx`, `components/calendar-workspace.tsx` and `components/compare-workspace.tsx` are therefore untouched by this feature.
-
-## Exports
-
-- **ICS** (`app/api/export/ics/route.ts:119`): visible, non-empty values are appended to `event.description` as `Label: value` lines, after the note.
-- **PDF** (`app/api/export/pdf/route.ts:278`): same position and the same `splitTextToSize` wrapping as the notes block. No new column — the fixed-width column layout around line 246 stays untouched.
-
-Both exports include every field with a value, not only `showInCalendar` ones; the constraint there is cell width, which does not apply to a document.
-
-## Audit logging
-
-New metadata interfaces in `lib/audit-log.ts`, added to the discriminated union rather than passed as loose objects:
-
-```ts
-export interface CustomFieldCreatedMetadata { calendarId, calendarName, fieldKey, fieldLabel, fieldType }
-export interface CustomFieldUpdatedMetadata { calendarId, calendarName, fieldKey, changes }
-export interface CustomFieldDeletedMetadata { calendarId, calendarName, fieldKey, fieldLabel, affectedShifts, affectedPresets }
-```
-
-Logged through `logUserAction` from the catalog routes. Setting values is not audited separately — it is part of the shift/preset edit that is already logged.
-
-## Edge cases
-
-| Case | Behaviour |
-|---|---|
-| Definition deleted | `ON DELETE CASCADE` removes every value. The confirm dialog names the number of affected shifts and presets first. |
-| Type change requested | Not allowed. `text` → `number` would make stored values unreadable. The sheet offers delete-and-recreate instead. |
-| `required` turned on later | Applies to new writes only; existing shifts are not retroactively invalid and are not blocked from other edits. |
-| `key` collision | Rejected with 409 and a field-level error in the form. |
-| Stale client catalog | Unknown keys in a write are dropped, not rejected. |
-| Synced shift | Values are read-only; `createEventFingerprint` is unchanged, so a sync run neither reads nor overwrites them. |
-| Calendar deleted | Cascades through `calendarId` on the definitions and through both child tables. |
-| Guest with a share link | May read values, may set them if their bundle grants shift editing, may never edit the catalog. |
-
-## Testing
-
-There is no unit-test framework in this repo; the gate is `npm test` (lint + build + i18n). Beyond that, the manual pass before opening the PR:
-
-1. `npm run db:generate` + `npm run db:migrate` apply cleanly on an existing database with shifts and presets.
-2. One field of each of the five types created, reordered, renamed; `key` and `type` are not editable.
-3. A preset value pre-fills a shift stamped from that preset; editing the preset afterwards leaves the shift alone.
-4. `GET /api/shifts?calendarId=…` returns `customFields` keyed by `key` with parsed types.
-5. Toggling `showInCalendar` changes the month and week cells; row height stays correct with several fields on one shift.
-6. Deleting a definition removes its values from every shift and preset.
-7. A share-link guest cannot reach the catalog routes (403) but sees the values.
-8. PDF and ICS exports contain the values.
-9. `AUTH_ENABLED=false` still allows catalog management.
-
-## Delivery
-
-One branch `feat/custom-fields`, Conventional Commits, split roughly as: schema + `lib/custom-fields.ts` + capability → API routes → client hooks + manage sheet → form integration → day detail and grids → exports. German i18n keys land with the commit that uses them; the other five locales follow in the same commit so `npm run i18n` stays green.