// Recurrence rules. Completing a repeating task spawns the next occurrence // (see store.updateTask) — the done row keeps its history, the clone carries // the rule forward. import { fromIso, toIso } from "./dates"; import type { Repeat } from "./types"; export const REPEATS: Repeat[] = ["daily", "weekdays", "weekly", "monthly", "yearly"]; export const REPEAT_LABEL: Record = { daily: "Daily", weekdays: "Weekdays", weekly: "Weekly", monthly: "Monthly", yearly: "Yearly", }; function addDays(d: Date, n: number): Date { const r = new Date(d); r.setDate(r.getDate() + n); return r; } /** Same day-of-month n months later, clamped to the month's last day. */ function addMonthsClamped(d: Date, n: number): Date { const r = new Date(d.getFullYear(), d.getMonth() + n, 1); const last = new Date(r.getFullYear(), r.getMonth() + 1, 0).getDate(); r.setDate(Math.min(d.getDate(), last)); return r; } function step(d: Date, repeat: Repeat): Date { switch (repeat) { case "daily": return addDays(d, 1); case "weekdays": { let n = addDays(d, 1); while (n.getDay() === 0 || n.getDay() === 6) n = addDays(n, 1); return n; } case "weekly": return addDays(d, 7); case "monthly": return addMonthsClamped(d, 1); case "yearly": return addMonthsClamped(d, 12); } } /** * Next occurrence strictly after the base date, catching up to today for * lapsed tasks (a monthly bill 3 months overdue advances to the next * anchor-day on or after today, not three stale dates in the past). */ export function nextOccurrence(baseIso: string | null, repeat: Repeat, todayIsoStr: string): string { let d = fromIso(baseIso ?? todayIsoStr); let guard = 0; do { d = step(d, repeat); } while (toIso(d) < todayIsoStr && ++guard < 5000); return toIso(d); } export function shiftDays(dateIso: string, n: number): string { return toIso(addDays(fromIso(dateIso), n)); }