feat(schedules): replace month grid with sliding swimlane timeline view

- Add MonthSwimlaneView with pinned schedule lanes, daily load header, today guide line, and hover preview bar.
- Merge consecutive execution days into continuous time-labeled horizontal bars with per-day click/hover regions.
- Wire 31-day rolling horizontal continuous track slider into ScheduleCalendarWorkspace for smooth cross-month swiping.
- Add bilingual i18n keys and register MonthSwimlaneView in migrated-page i18n checks.
This commit is contained in:
ji ruo committed 2026-12-03 17:14:39 +08:00
1 parent 7a10645012
commit dea5385661
4 files changed
+848 -173

No files matched your search

@@ -0,0 +1,772 @@
"use client";
import * as React from "react";
import { ChevronDownIcon, ChevronRightIcon, PlusIcon } from "lucide-react";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { type CalendarEventOccurrence, makeDateKey, parseDateKey, weekdayOfDateKey } from "@/lib/schedule-calendar";
import type { TaskSchedule } from "@/lib/types";
import { cn } from "@/lib/utils";
interface StatusVisual {
dot: string;
accent: string;
bar: string;
barOnce: string;
barSelected: string;
}
const LANE_STATUS_VISUAL: Record<TaskSchedule["status"], StatusVisual> = {
running: {
dot: "bg-emerald-500",
accent: "bg-emerald-500",
bar: "bg-emerald-500/16 border-emerald-500/35 text-emerald-950 dark:bg-emerald-500/22 dark:border-emerald-400/40 dark:text-emerald-100",
barOnce: "bg-emerald-500/90 border-emerald-600 text-white dark:bg-emerald-600 dark:border-emerald-400",
barSelected: "ring-2 ring-emerald-500 ring-offset-1 ring-offset-background",
},
waiting: {
dot: "bg-blue-500",
accent: "bg-blue-500",
bar: "bg-blue-500/12 border-blue-500/30 text-blue-950 dark:bg-blue-500/20 dark:border-blue-400/35 dark:text-blue-100",
barOnce: "bg-indigo-500/90 border-indigo-600 text-white dark:bg-indigo-600 dark:border-indigo-400",
barSelected: "ring-2 ring-blue-500 ring-offset-1 ring-offset-background",
},
outside: {
dot: "bg-orange-500",
accent: "bg-orange-500",
bar: "bg-orange-500/14 border-orange-500/35 text-orange-950 dark:bg-orange-500/20 dark:border-orange-400/40 dark:text-orange-100",
barOnce: "bg-orange-500/90 border-orange-600 text-white dark:bg-orange-600 dark:border-orange-400",
barSelected: "ring-2 ring-orange-500 ring-offset-1 ring-offset-background",
},
completed: {
dot: "bg-sky-500",
accent: "bg-sky-500",
bar: "bg-sky-500/14 border-sky-500/30 text-sky-950 dark:bg-sky-500/20 dark:border-sky-400/35 dark:text-sky-100",
barOnce: "bg-sky-600/90 border-sky-700 text-white dark:bg-sky-600 dark:border-sky-400",
barSelected: "ring-2 ring-sky-500 ring-offset-1 ring-offset-background",
},
paused: {
dot: "bg-slate-400",
accent: "bg-slate-400",
bar: "bg-slate-400/15 border-slate-400/35 text-slate-700 dark:bg-slate-500/20 dark:border-slate-500/40 dark:text-slate-300",
barOnce: "bg-slate-500/80 border-slate-600 text-white",
barSelected: "ring-2 ring-slate-400 ring-offset-1 ring-offset-background",
},
error: {
dot: "bg-rose-500",
accent: "bg-rose-500",
bar: "bg-rose-500/16 border-rose-500/40 text-rose-950 dark:bg-rose-500/24 dark:border-rose-400/45 dark:text-rose-100",
barOnce: "bg-rose-600/90 border-rose-700 text-white dark:bg-rose-600 dark:border-rose-400",
barSelected: "ring-2 ring-rose-500 ring-offset-1 ring-offset-background",
},
};
const STATUS_SORT_RANK: Record<TaskSchedule["status"], number> = {
running: 0,
error: 1,
waiting: 2,
outside: 3,
completed: 4,
paused: 5,
};
export interface MonthSlideBinding {
containerRef: React.RefObject<HTMLDivElement | null>;
viewportRef: React.MutableRefObject<HTMLDivElement | null>;
headerTrackRef: React.RefObject<HTMLDivElement | null>;
gridTrackRef: React.RefObject<HTMLDivElement | null>;
onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => void;
onClickCapture: (e: React.MouseEvent<HTMLDivElement>) => void;
}
interface SwimlaneSpan {
key: string;
startIdx: number;
spanDays: number;
occurrences: CalendarEventOccurrence[];
startDateKey: string;
endDateKey: string;
overnight: boolean;
continuesBeforeTrack: boolean;
continuesAfterTrack: boolean;
}
interface SwimlaneRowData {
schedule: TaskSchedule;
spans: SwimlaneSpan[];
visibleDayCount: number;
firstVisibleOccurrence: CalendarEventOccurrence | null;
}
function cadenceKey(schedule: TaskSchedule): string {
if (schedule.schedule_type === "once") return "schedule.month.cadenceOnce";
const wds = [...new Set(schedule.weekdays)].sort((a, b) => a - b);
if (wds.length === 7) return "schedule.month.cadenceDaily";
if (wds.length === 5 && wds[0] === 1 && wds[4] === 5) return "schedule.month.cadenceWeekdays";
if (wds.length === 2 && wds[0] === 6 && wds[1] === 7) return "schedule.month.cadenceWeekends";
return "schedule.month.cadenceWeekly";
}
function formatScheduleWindow(schedule: TaskSchedule): string {
const start = schedule.start_time.slice(0, 5);
if (!schedule.end_time) return `${start} →`;
return `${start}–${schedule.end_time.slice(0, 5)}`;
}
function buildRowSpans(
schedule: TaskSchedule,
scheduleOccs: CalendarEventOccurrence[],
dayIndexByKey: Map<string, number>,
trackDateKeys: string[],
visibleStartIdx: number,
visibleEndIdx: number,
): {
spans: SwimlaneSpan[];
visibleDayCount: number;
firstVisibleOccurrence: CalendarEventOccurrence | null;
activeIndices: number[];
} {
if (scheduleOccs.length === 0) {
return { spans: [], visibleDayCount: 0, firstVisibleOccurrence: null, activeIndices: [] };
}
const isMultiDayOnce =
schedule.schedule_type === "once" &&
Boolean(schedule.run_date && schedule.end_date && schedule.end_date > schedule.run_date);
// Pick primary occurrence per day index along the entire sliding track.
const occByDay = new Map<number, CalendarEventOccurrence>();
for (const occ of scheduleOccs) {
const idx = dayIndexByKey.get(occ.dateKey);
if (idx === undefined) continue;
// Skip pure overnight continuation spill on day D+1 for non-multiday schedules so Wed-Fri overnight stays Wed-Fri.
if (!isMultiDayOnce && occ.isContinuedFromPrev && idx > 0) continue;
const prev = occByDay.get(idx);
if (!prev || (prev.isContinuedFromPrev && !occ.isContinuedFromPrev)) {
occByDay.set(idx, occ);
}
}
const sortedIndices = [...occByDay.keys()].sort((a, b) => a - b);
const spans: SwimlaneSpan[] = [];
let visibleDayCount = 0;
let firstVisibleOccurrence: CalendarEventOccurrence | null = null;
let i = 0;
while (i < sortedIndices.length) {
const startIdx = sortedIndices[i];
let endIdx = startIdx;
const spanOccs: CalendarEventOccurrence[] = [];
const first = occByDay.get(startIdx);
if (first) spanOccs.push(first);
// Merge consecutive active days into one clean horizontal timeline bar (e.g., Mon-Fri, Wed-Fri, Sat-Sun, multi-day once).
while (i + 1 < sortedIndices.length && sortedIndices[i + 1] === endIdx + 1) {
i++;
endIdx = sortedIndices[i];
const next = occByDay.get(endIdx);
if (next) spanOccs.push(next);
}
if (spanOccs.length > 0) {
for (let d = startIdx; d <= endIdx; d++) {
if (d >= visibleStartIdx && d < visibleEndIdx) {
visibleDayCount++;
if (!firstVisibleOccurrence) {
firstVisibleOccurrence = occByDay.get(d) ?? null;
}
}
}
const lastOcc = spanOccs[spanOccs.length - 1];
spans.push({
key: `${schedule.id}:span:${trackDateKeys[startIdx]}:${endIdx - startIdx + 1}`,
startIdx,
spanDays: endIdx - startIdx + 1,
occurrences: spanOccs,
startDateKey: trackDateKeys[startIdx],
endDateKey: trackDateKeys[endIdx],
overnight: !isMultiDayOnce && Boolean(lastOcc.isContinuesToNext && !lastOcc.allDay),
continuesBeforeTrack: Boolean(startIdx === 0 && spanOccs[0].isContinuedFromPrev),
continuesAfterTrack: Boolean(endIdx === trackDateKeys.length - 1 && lastOcc.isContinuesToNext),
});
}
i++;
}
return {
spans,
visibleDayCount,
firstVisibleOccurrence: firstVisibleOccurrence ?? spans[0]?.occurrences[0] ?? null,
activeIndices: sortedIndices,
};
}
export function MonthSwimlaneView({
slide,
trackDateKeys,
visibleStartIdx,
visibleCount,
dominantMonth,
monthShortFmt,
todayKey,
anchorDateKey,
schedules,
occurrences,
selectedOccurrenceId,
onSelectOccurrence,
onSelectDay,
onCreateAtSlot,
}: {
slide: MonthSlideBinding;
trackDateKeys: string[];
visibleStartIdx: number;
visibleCount: number;
dominantMonth: { year: number; month: number };
monthShortFmt: Intl.DateTimeFormat;
todayKey: string;
anchorDateKey: string;
schedules: TaskSchedule[];
occurrences: CalendarEventOccurrence[];
selectedOccurrenceId: string | null;
onSelectOccurrence: (occ: CalendarEventOccurrence) => void;
onSelectDay: (dateKey: string) => void;
onCreateAtSlot: (dateKey: string, startMin: number, endMin: number) => void;
}) {
const { t: translate } = useLiveTranslation();
const [showInactive, setShowInactive] = React.useState(false);
const [hoveredInfo, setHoveredInfo] = React.useState<{
schedule: TaskSchedule;
occ: CalendarEventOccurrence;
span: SwimlaneSpan;
} | null>(null);
const totalCols = trackDateKeys.length;
const visibleEndIdx = visibleStartIdx + visibleCount;
const trackDays = React.useMemo(
() =>
trackDateKeys.map((dateKey, idx) => {
const p = parseDateKey(dateKey);
const weekday = weekdayOfDateKey(dateKey);
const day = p ? p.day : 1;
const inDominantMonth = p?.year === dominantMonth.year && p?.month === dominantMonth.month;
const shortMonth = day === 1 && p ? monthShortFmt.format(new Date(Date.UTC(p.year, p.month - 1, 15))) : "";
return {
idx,
day,
dateKey,
weekday,
isWeekend: weekday === 6 || weekday === 7,
isToday: dateKey === todayKey,
isAnchor: dateKey === anchorDateKey,
isMonthStart: day === 1,
inDominantMonth,
shortMonth,
};
}),
[trackDateKeys, dominantMonth.year, dominantMonth.month, monthShortFmt, todayKey, anchorDateKey],
);
const { activeRows, inactiveRows, dayLoads, maxDayLoad, totalVisibleRuns } = React.useMemo(() => {
const dayIndexByKey = new Map<string, number>();
for (const d of trackDays) dayIndexByKey.set(d.dateKey, d.idx);
const occsBySchedule = new Map<number, CalendarEventOccurrence[]>();
for (const occ of occurrences) {
if (!dayIndexByKey.has(occ.dateKey)) continue;
const list = occsBySchedule.get(occ.scheduleId);
if (list) list.push(occ);
else occsBySchedule.set(occ.scheduleId, [occ]);
}
const loads = Array.from({ length: trackDays.length }, () => 0);
const active: SwimlaneRowData[] = [];
const inactive: SwimlaneRowData[] = [];
let runs = 0;
for (const schedule of schedules) {
const built = buildRowSpans(
schedule,
occsBySchedule.get(schedule.id) ?? [],
dayIndexByKey,
trackDateKeys,
visibleStartIdx,
visibleEndIdx,
);
for (const idx of built.activeIndices) {
loads[idx]++;
}
const row: SwimlaneRowData = {
schedule,
spans: built.spans,
visibleDayCount: built.visibleDayCount,
firstVisibleOccurrence: built.firstVisibleOccurrence,
};
if (built.visibleDayCount > 0) {
active.push(row);
runs += built.visibleDayCount;
} else {
inactive.push(row);
}
}
const compareRows = (a: SwimlaneRowData, b: SwimlaneRowData) => {
const rankDiff = (STATUS_SORT_RANK[a.schedule.status] ?? 9) - (STATUS_SORT_RANK[b.schedule.status] ?? 9);
if (rankDiff !== 0) return rankDiff;
const typeDiff = (a.schedule.schedule_type === "once" ? 0 : 1) - (b.schedule.schedule_type === "once" ? 0 : 1);
if (typeDiff !== 0) return typeDiff;
const timeDiff = a.schedule.start_time.localeCompare(b.schedule.start_time);
if (timeDiff !== 0) return timeDiff;
return a.schedule.name.localeCompare(b.schedule.name);
};
active.sort(compareRows);
inactive.sort(compareRows);
const visibleLoads = loads.slice(visibleStartIdx, visibleEndIdx);
return {
activeRows: active,
inactiveRows: inactive,
dayLoads: loads,
maxDayLoad: Math.max(...visibleLoads, 1),
totalVisibleRuns: runs,
};
}, [trackDays, trackDateKeys, occurrences, schedules, visibleStartIdx, visibleEndIdx]);
const todayIdx = trackDays.findIndex((d) => d.isToday);
const trackWidthPct = (totalCols / Math.max(visibleCount, 1)) * 100;
const headerTrackStyle = React.useMemo<React.CSSProperties>(
() => ({
width: `${trackWidthPct}%`,
gridTemplateColumns: `repeat(${totalCols}, minmax(0, 1fr))`,
}),
[trackWidthPct, totalCols],
);
const gridTrackOuterStyle = React.useMemo<React.CSSProperties>(
() => ({
width: `${trackWidthPct}%`,
}),
[trackWidthPct],
);
const dayGridColsStyle = React.useMemo<React.CSSProperties>(
() => ({
gridTemplateColumns: `repeat(${totalCols}, minmax(0, 1fr))`,
}),
[totalCols],
);
const openScheduleDetail = (row: SwimlaneRowData) => {
if (row.firstVisibleOccurrence) {
onSelectOccurrence(row.firstVisibleOccurrence);
return;
}
const fallbackDate =
row.schedule.run_date && row.schedule.run_date.length > 0
? row.schedule.run_date
: makeDateKey(dominantMonth.year, dominantMonth.month, 1);
onSelectOccurrence({
id: `${row.schedule.id}:${fallbackDate}:lane`,
scheduleId: row.schedule.id,
schedule: row.schedule,
dateKey: fallbackDate,
startMin: 0,
endMin: 60,
allDay: !row.schedule.end_time,
displayTimeRange: formatScheduleWindow(row.schedule),
});
};
const renderLeftLabel = (row: SwimlaneRowData, muted = false) => {
const { schedule } = row;
const vis = LANE_STATUS_VISUAL[schedule.status] ?? LANE_STATUS_VISUAL.waiting;
const isOnce = schedule.schedule_type === "once";
const cadenceLabel = translate(cadenceKey(schedule));
const windowText = formatScheduleWindow(schedule);
return (
<button
key={schedule.id}
type="button"
onClick={() => openScheduleDetail(row)}
className={cn(
"flex h-[46px] w-full items-center gap-2 border-border/50 border-b bg-background px-3 text-left transition-colors hover:bg-muted/30",
muted && "opacity-55",
)}
title={`${schedule.name} · ${windowText}`}
>
<span className="relative flex size-2 shrink-0 items-center justify-center">
{schedule.status === "running" && (
<span className="absolute inline-flex size-2.5 animate-ping rounded-full bg-emerald-400 opacity-60" />
)}
<span className={cn("relative size-2 rounded-full", vis.dot)} />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-1.5">
<span className="truncate font-medium text-xs leading-tight">{schedule.name}</span>
{row.visibleDayCount > 0 && (
<span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">
{translate("schedule.month.runDays", { count: row.visibleDayCount })}
</span>
)}
</div>
<div className="mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground">
<span
className={cn(
"shrink-0 rounded px-1 py-0 font-medium text-[9px]",
isOnce
? "bg-indigo-500/12 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-300"
: "bg-muted text-muted-foreground",
)}
>
{cadenceLabel}
</span>
<span className="truncate font-mono tabular-nums">{windowText}</span>
{schedule.task_ids.length > 0 && (
<span className="ml-auto shrink-0 font-mono text-[9px] tabular-nums opacity-75">
#{schedule.task_ids.length}
</span>
)}
</div>
</div>
</button>
);
};
const renderTrackRow = (row: SwimlaneRowData, muted = false) => {
const { schedule } = row;
const vis = LANE_STATUS_VISUAL[schedule.status] ?? LANE_STATUS_VISUAL.waiting;
const isOnce = schedule.schedule_type === "once";
const windowText = formatScheduleWindow(schedule);
const shortStart = schedule.start_time.slice(0, 5);
return (
<div
key={schedule.id}
className={cn(
"relative h-[46px] border-border/50 border-b transition-colors hover:bg-muted/15",
muted && "opacity-55",
)}
>
{/* Background clickable day cells */}
<div className="grid h-full" style={dayGridColsStyle}>
{trackDays.map((d) => (
<button
key={d.dateKey}
type="button"
aria-label={translate("schedule.month.createAtDay", { date: d.dateKey })}
onClick={() => onCreateAtSlot(d.dateKey, 9 * 60, 10 * 60)}
className={cn(
"group/cell relative border-border/25 border-r transition-colors last:border-r-0 hover:bg-accent/35",
d.isMonthStart && "border-l border-l-border/80",
d.isWeekend && "bg-muted/20",
d.isToday && "bg-blue-500/[0.045]",
)}
>
<PlusIcon className="pointer-events-none absolute top-1/2 left-1/2 size-3 -translate-x-1/2 -translate-y-1/2 text-muted-foreground/40 opacity-0 transition-opacity group-hover/cell:opacity-100" />
</button>
))}
</div>
{/* Continuous merged horizontal bars */}
{row.spans.length > 0 && (
<div className="pointer-events-none absolute inset-0 grid items-center py-2" style={dayGridColsStyle}>
{row.spans.map((span) => {
const anySelected = span.occurrences.some((o) => o.id === selectedOccurrenceId);
const barLabel = span.spanDays >= 2 ? windowText : shortStart;
return (
<div
key={span.key}
style={{ gridColumn: `${span.startIdx + 1} / span ${span.spanDays}` }}
className="pointer-events-auto flex h-full items-center px-[2px]"
>
<div
className={cn(
"relative flex h-6 w-full items-center overflow-hidden border transition-all",
span.continuesBeforeTrack ? "rounded-l-none border-l-dashed" : "rounded-l-[5px]",
span.continuesAfterTrack ? "rounded-r-none border-r-dashed" : "rounded-r-[5px]",
isOnce ? vis.barOnce : vis.bar,
anySelected && vis.barSelected,
)}
>
{/* Crisp left accent edge for recurring bars */}
{!isOnce && (
<span
aria-hidden="true"
className={cn("pointer-events-none absolute inset-y-0 left-0 w-[3px]", vis.accent)}
/>
)}
{/* Per-day interactive slices inside the continuous bar */}
<div
className="grid h-full w-full divide-x divide-current/10"
style={{ gridTemplateColumns: `repeat(${span.spanDays}, minmax(0, 1fr))` }}
>
{span.occurrences.map((occ) => {
const dateLabel =
span.spanDays > 1 && isOnce ? `${span.startDateKey} → ${span.endDateKey}` : occ.dateKey;
const titleText = `${schedule.name}\n${dateLabel} · ${occ.displayTimeRange}${
span.overnight ? ` (${translate("schedule.month.overnight")})` : ""
}`;
return (
<button
key={occ.id}
type="button"
title={titleText}
onMouseEnter={() => setHoveredInfo({ schedule, occ, span })}
onMouseLeave={() => setHoveredInfo((cur) => (cur?.occ.id === occ.id ? null : cur))}
onClick={(e) => {
e.stopPropagation();
onSelectOccurrence(occ);
}}
className="h-full w-full cursor-pointer transition-colors hover:bg-current/10"
/>
);
})}
</div>
{/* Centered readable time window label (no mystery dots) */}
<span
className={cn(
"pointer-events-none absolute inset-0 flex items-center justify-center truncate px-1.5 font-medium font-mono tracking-tight",
span.spanDays >= 2 ? "text-[10px]" : "text-[9px]",
)}
>
{barLabel}
</span>
{/* Subtle right edge indicator for overnight runs */}
{span.overnight && (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 right-0 w-[3px] bg-current opacity-35"
/>
)}
</div>
</div>
);
})}
</div>
)}
</div>
);
};
return (
<div
key="month"
ref={slide.containerRef}
onPointerDown={slide.onPointerDown}
onClickCapture={slide.onClickCapture}
className="flex min-h-0 min-w-0 flex-1 touch-pan-y select-none flex-col overflow-hidden overscroll-x-contain bg-background"
>
{/* Sticky top header row: fixed left lane header + continuously sliding day header track */}
<div
className="grid shrink-0 border-b bg-background/95 backdrop-blur-xs"
style={{ gridTemplateColumns: "236px minmax(0, 1fr)" }}
>
<div className="flex flex-col justify-center border-r px-3 py-2">
<div className="flex items-center justify-between gap-2">
<span className="font-semibold text-xs">{translate("schedule.month.laneTitle")}</span>
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground tabular-nums">
{activeRows.length}/{schedules.length}
</span>
</div>
<span className="mt-0.5 truncate text-[10px] text-muted-foreground">
{translate("schedule.month.laneHint")}
</span>
</div>
<div ref={slide.viewportRef} className="min-w-0 overflow-hidden">
<div ref={slide.headerTrackRef} className="grid will-change-transform" style={headerTrackStyle}>
{trackDays.map((d) => {
const load = dayLoads[d.idx] ?? 0;
const loadRatio = load > 0 ? Math.max(0.2, load / maxDayLoad) : 0;
let loadBarClass = "bg-blue-500/45";
if (load >= 5) loadBarClass = "bg-amber-500/80";
else if (load >= 3) loadBarClass = "bg-blue-500/75";
return (
<div
key={d.dateKey}
className={cn(
"flex flex-col items-center border-border/30 border-r pt-1.5 pb-1 last:border-r-0",
d.isMonthStart && "border-l border-l-border/80",
d.isWeekend && "bg-muted/25",
d.isToday && "bg-blue-500/[0.06]",
!d.inDominantMonth && "opacity-65",
)}
>
<span
className={cn(
"text-[10px] text-muted-foreground leading-none",
d.isWeekend && "text-muted-foreground/70",
d.isMonthStart && "font-semibold text-foreground/80",
d.isToday && "font-semibold text-blue-600 dark:text-blue-400",
)}
>
{d.isMonthStart ? d.shortMonth : translate(`schedule.calendar.weekdayShort.${d.weekday}`)}
</span>
<button
type="button"
data-calendar-event="true"
onClick={() => onSelectDay(d.dateKey)}
className={cn(
"mt-1 flex size-6 items-center justify-center rounded-full font-medium text-xs tabular-nums transition-colors hover:bg-accent",
d.isAnchor && !d.isToday && "ring-1 ring-blue-500/50",
d.isToday && "bg-blue-600 text-white hover:bg-blue-700",
)}
>
{d.day}
</button>
{/* Daily load density micro-indicator */}
<div
className="mt-1 flex h-3.5 w-full flex-col items-center justify-end px-1"
title={load > 0 ? translate("schedule.calendar.dayEventCount", { count: load }) : undefined}
>
{load > 0 && (
<>
<span className="font-mono text-[8px] text-muted-foreground tabular-nums leading-none">
{load}
</span>
<div className="mt-0.5 h-1 w-full overflow-hidden rounded-full bg-muted/80">
<div
className={cn("h-full rounded-full", loadBarClass)}
style={{ width: `${Math.round(loadRatio * 100)}%` }}
/>
</div>
</>
)}
</div>
</div>
);
})}
</div>
</div>
</div>
{/* Vertically scrollable swimlane body: fixed left labels + synchronized horizontal sliding track */}
{schedules.length === 0 ? (
<div className="flex flex-1 items-center justify-center p-10 text-muted-foreground text-sm">
{translate("schedule.month.empty")}
</div>
) : (
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
<div className="grid min-h-full" style={{ gridTemplateColumns: "236px minmax(0, 1fr)" }}>
{/* Left column: pinned schedule labels */}
<div className="flex flex-col border-r bg-background">
{activeRows.map((row) => renderLeftLabel(row, false))}
{inactiveRows.length > 0 && (
<>
<button
type="button"
onClick={() => setShowInactive((v) => !v)}
className="flex h-[30px] w-full items-center gap-1.5 border-b bg-muted/25 px-3 text-left font-medium text-[11px] text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground"
>
{showInactive ? (
<ChevronDownIcon className="size-3.5 shrink-0" />
) : (
<ChevronRightIcon className="size-3.5 shrink-0" />
)}
<span className="truncate">
{translate("schedule.month.inactiveGroup", { count: inactiveRows.length })}
</span>
</button>
{showInactive && inactiveRows.map((row) => renderLeftLabel(row, true))}
</>
)}
<div className="flex-1" />
</div>
{/* Right column: clipped viewport + single GPU sliding track */}
<div className="relative min-w-0 overflow-hidden">
<div
ref={slide.gridTrackRef}
className="relative flex min-h-full flex-col will-change-transform"
style={gridTrackOuterStyle}
>
{activeRows.map((row) => renderTrackRow(row, false))}
{inactiveRows.length > 0 && (
<>
<div className="h-[30px] border-b bg-muted/20" />
{showInactive && inactiveRows.map((row) => renderTrackRow(row, true))}
</>
)}
{/* Remaining vertical background columns */}
<div className="grid flex-1" style={dayGridColsStyle}>
{trackDays.map((d) => (
<div
key={d.dateKey}
className={cn(
"border-border/20 border-r last:border-r-0",
d.isMonthStart && "border-l border-l-border/70",
d.isWeekend && "bg-muted/15",
d.isToday && "bg-blue-500/[0.03]",
)}
/>
))}
</div>
{/* Full-height today vertical guide line */}
{todayIdx >= 0 && (
<div
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 z-10 w-[1.5px] bg-blue-500/55"
style={{ left: `${((todayIdx + 0.5) / totalCols) * 100}%` }}
/>
)}
</div>
</div>
</div>
</div>
)}
{/* Bottom status / hover preview bar */}
<div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-t bg-muted/15 px-3 py-1.5 text-[11px] text-muted-foreground">
{hoveredInfo ? (
<div className="flex min-w-0 items-center gap-2 text-foreground">
<span
className={cn(
"size-2 shrink-0 rounded-full",
(LANE_STATUS_VISUAL[hoveredInfo.schedule.status] ?? LANE_STATUS_VISUAL.waiting).dot,
)}
/>
<span className="truncate font-medium">{hoveredInfo.schedule.name}</span>
<span className="shrink-0 font-mono text-muted-foreground tabular-nums">
{hoveredInfo.span.spanDays > 1 && hoveredInfo.schedule.schedule_type === "once"
? `${hoveredInfo.span.startDateKey} → ${hoveredInfo.span.endDateKey}`
: hoveredInfo.occ.dateKey}
</span>
<span className="shrink-0 font-mono tabular-nums">{hoveredInfo.occ.displayTimeRange}</span>
{hoveredInfo.span.overnight && (
<span className="rounded bg-muted px-1 py-0 text-[10px] text-muted-foreground">
{translate("schedule.month.overnight")}
</span>
)}
</div>
) : (
<div className="flex flex-wrap items-center gap-3">
{(["running", "waiting", "outside", "completed", "paused", "error"] as const).map((st) => (
<span key={st} className="inline-flex items-center gap-1">
<span className={cn("size-1.5 rounded-full", LANE_STATUS_VISUAL[st].dot)} />
<span>{translate(`schedule.status.${st}`)}</span>
</span>
))}
<span className="hidden text-muted-foreground/70 md:inline">
· {translate("schedule.calendar.swipeHint")}
</span>
</div>
)}
<span className="shrink-0 font-mono text-[10px] tabular-nums">
{translate("schedule.month.footerSummary", { active: activeRows.length, runs: totalVisibleRuns })}
</span>
</div>
</div>
);
}
@@ -58,6 +58,7 @@ import {
import { scheduleDisplay } from "@/lib/schedule-display";
import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types";
import { cn } from "@/lib/utils";
import { MonthSwimlaneView } from "./month-swimlane-view";
const EXPANDED_HOUR_HEIGHT = 52; // px per hour in expanded mode
const MIN_FIT_HOUR_HEIGHT = 22; // minimum px per hour in auto-fit mode
@@ -671,9 +672,9 @@ export function ScheduleCalendarWorkspace({
const [viewMode, setViewMode] = React.useState<CalendarViewMode>("week");
const [anchorDateKey, setAnchorDateKey] = React.useState<string>(todayKey);
const [weekStartDateKey, setWeekStartDateKey] = React.useState<string>(() => startOfWeekDateKey(todayKey));
const [monthStartWeekKey, setMonthStartWeekKey] = React.useState<string>(() => {
const [monthStartDateKey, setMonthStartDateKey] = React.useState<string>(() => {
const p = parseDateKey(todayKey);
return startOfWeekDateKey(p ? makeDateKey(p.year, p.month, 1) : todayKey);
return p ? makeDateKey(p.year, p.month, 1) : todayKey;
});
const [yearStartQuarter, setYearStartQuarter] = React.useState<{ year: number; month: number }>(() => {
const p = parseDateKey(todayKey);
@@ -685,8 +686,8 @@ export function ScheduleCalendarWorkspace({
setWeekStartDateKey(startOfWeekDateKey(dk));
const p = parseDateKey(dk);
if (p) {
setMonthStartWeekKey(startOfWeekDateKey(makeDateKey(p.year, p.month, 1)));
setYearStartQuarter({ year: p.year, month: 1 });
setMonthStartDateKey(makeDateKey(p.year, p.month, 1));
}
}, []);
const initializedAnchor = React.useRef(false);
@@ -824,22 +825,20 @@ export function ScheduleCalendarWorkspace({
[searchMatchedSchedules, enabledStatuses],
);
// Visible date keys for current view (Week uses rolling 7-day window starting at weekStartDateKey).
const monthVisibleRows = 6;
const monthBufferRows = 6;
const monthTotalRows = monthVisibleRows + monthBufferRows * 2;
const monthVisibleCols = 31;
const monthBufferCols = 31;
const monthDominantParts = React.useMemo(() => {
const midKey = addDaysToDateKey(monthStartWeekKey, 2 * 7 + 3);
const midKey = addDaysToDateKey(monthStartDateKey, Math.floor(monthVisibleCols / 2));
return parseDateKey(midKey) ?? anchorParts;
}, [monthStartWeekKey, anchorParts]);
}, [monthStartDateKey, anchorParts]);
// Visible date keys for current view (Week uses rolling 7-day window; Month uses rolling 6-week window).
// Visible date keys for current view (Week uses rolling 7-day window; Month uses rolling 31-day swimlane window).
const visibleDateKeys = React.useMemo(() => {
if (viewMode === "day") return [anchorDateKey];
if (viewMode === "week") return buildRollingDateKeys(weekStartDateKey, 7);
if (viewMode === "month") return buildRollingDateKeys(monthStartWeekKey, monthVisibleRows * 7);
if (viewMode === "month") return buildRollingDateKeys(monthStartDateKey, monthVisibleCols);
return [];
}, [viewMode, anchorDateKey, weekStartDateKey, monthStartWeekKey]);
}, [viewMode, anchorDateKey, weekStartDateKey, monthStartDateKey]);
const timeGridVisibleCols = viewMode === "day" ? 1 : 7;
const timeGridBufferCols = viewMode === "day" ? 3 : 7;
@@ -864,30 +863,19 @@ export function ScheduleCalendarWorkspace({
[locale],
);
// Month view: 18 continuous week rows [6 buffer above, 6 visible, 6 buffer below] so each week glides 1:1.
const monthTrackWeeks = React.useMemo(() => {
const monthTrackDateKeys = React.useMemo(() => {
if (viewMode !== "month") return [];
const startKey = addDaysToDateKey(monthStartWeekKey, -monthBufferRows * 7);
return Array.from({ length: monthTotalRows }, (_, rowIdx) => {
const weekStart = addDaysToDateKey(startKey, rowIdx * 7);
return {
weekStart,
days: buildRollingDateKeys(weekStart, 7),
};
});
}, [viewMode, monthStartWeekKey, monthTotalRows]);
return buildRollingDateKeys(
addDaysToDateKey(monthStartDateKey, -monthBufferCols),
monthVisibleCols + monthBufferCols * 2,
);
}, [viewMode, monthStartDateKey]);
const occurrenceDateKeys = React.useMemo(() => {
if (viewMode === "day" || viewMode === "week") return timeGridDateKeys;
if (viewMode === "month") {
const keys: string[] = [];
for (const row of monthTrackWeeks) {
for (const dk of row.days) keys.push(dk);
}
return keys;
}
if (viewMode === "month") return monthTrackDateKeys;
return visibleDateKeys;
}, [viewMode, timeGridDateKeys, monthTrackWeeks, visibleDateKeys]);
}, [viewMode, timeGridDateKeys, monthTrackDateKeys, visibleDateKeys]);
const occurrences = React.useMemo(
() =>
@@ -1072,12 +1060,12 @@ export function ScheduleCalendarWorkspace({
[viewMode],
);
const shiftMonthWeeks = React.useCallback((deltaWeeks: number) => {
if (deltaWeeks === 0) return;
const shiftMonthDays = React.useCallback((deltaDays: number) => {
if (deltaDays === 0) return;
setExpandedOccId(null);
setMonthStartWeekKey((prev) => {
const next = addDaysToDateKey(prev, deltaWeeks * 7);
const mid = parseDateKey(addDaysToDateKey(next, 2 * 7 + 3));
setMonthStartDateKey((prev) => {
const next = addDaysToDateKey(prev, deltaDays);
const mid = parseDateKey(addDaysToDateKey(next, Math.floor(monthVisibleCols / 2)));
if (mid) {
const nextAnchor = makeDateKey(mid.year, mid.month, 1);
setAnchorDateKey(nextAnchor);
@@ -1095,7 +1083,7 @@ export function ScheduleCalendarWorkspace({
const nextAnchor = makeDateKey(next.year, next.month, 1);
setAnchorDateKey(nextAnchor);
setWeekStartDateKey(startOfWeekDateKey(nextAnchor));
setMonthStartWeekKey(startOfWeekDateKey(nextAnchor));
setMonthStartDateKey(nextAnchor);
return next;
});
}, []);
@@ -1140,13 +1128,12 @@ export function ScheduleCalendarWorkspace({
const monthSlide = useContinuousTrackSlider({
enabled: viewMode === "month" && !dragState && !expandDrag,
axis: "y",
crossAxisWheel: true,
axis: "x",
attachKey: viewMode === "month" ? "month" : "",
visibleUnits: monthVisibleRows,
bufferUnits: monthBufferRows,
trackKey: monthStartWeekKey,
onShiftUnits: shiftMonthWeeks,
visibleUnits: monthVisibleCols,
bufferUnits: monthBufferCols,
trackKey: monthStartDateKey,
onShiftUnits: shiftMonthDays,
shouldIgnorePointerDown: (target) =>
Boolean(target?.closest('[data-calendar-event="true"], [data-no-calendar-swipe="true"], input, textarea, select')),
shouldIgnoreWheel: (target) =>
@@ -1195,9 +1182,7 @@ export function ScheduleCalendarWorkspace({
setExpandedOccId(null);
if (mode === "month") {
const p = parseDateKey(anchorDateKey);
if (p) {
setMonthStartWeekKey(startOfWeekDateKey(makeDateKey(p.year, p.month, 1)));
}
if (p) setMonthStartDateKey(makeDateKey(p.year, p.month, 1));
} else if (mode === "year") {
const p = parseDateKey(anchorDateKey);
if (p) {
@@ -1219,11 +1204,11 @@ export function ScheduleCalendarWorkspace({
timeGridSlide.slideByUnits(dir);
} else if (viewMode === "month") {
const target = addYearMonth(monthDominantParts.year, monthDominantParts.month, dir);
const targetStartWeek = startOfWeekDateKey(makeDateKey(target.year, target.month, 1));
const curMs = Date.parse(`${monthStartWeekKey}T00:00:00Z`);
const nextMs = Date.parse(`${targetStartWeek}T00:00:00Z`);
const deltaWeeks = Math.round((nextMs - curMs) / (7 * 86_400_000));
monthSlide.slideByUnits(deltaWeeks || dir * 4);
const targetFirst = makeDateKey(target.year, target.month, 1);
const curMs = Date.parse(`${monthStartDateKey}T00:00:00Z`);
const nextMs = Date.parse(`${targetFirst}T00:00:00Z`);
const deltaDays = Math.round((nextMs - curMs) / 86_400_000);
monthSlide.slideByUnits(deltaDays || dir * 30);
} else if (viewMode === "year") {
yearSlide.slideByUnits(dir * yearVisibleCols);
}
@@ -1235,7 +1220,7 @@ export function ScheduleCalendarWorkspace({
yearSlide.slideByUnits,
monthDominantParts.year,
monthDominantParts.month,
monthStartWeekKey,
monthStartDateKey,
yearVisibleCols,
],
);
@@ -1248,13 +1233,6 @@ export function ScheduleCalendarWorkspace({
}),
[timeGridTotalCols, timeGridVisibleCols],
);
const monthTrackStyle = React.useMemo<React.CSSProperties>(
() => ({
height: `${(monthTotalRows / monthVisibleRows) * 100}%`,
gridTemplateRows: `repeat(${monthTotalRows}, minmax(0, 1fr))`,
}),
[monthTotalRows, monthVisibleRows],
);
const yearTrackStyle = React.useMemo<React.CSSProperties>(
() => ({
width: `${(yearTotalCols / yearVisibleCols) * 100}%`,
@@ -2312,120 +2290,28 @@ export function ScheduleCalendarWorkspace({
</div>
</div>
) : viewMode === "month" ? (
/* Month Grid View: weekday header pinned; continuous week rows glide smoothly 1 row at a time */
<div
key="month"
ref={monthSlide.containerRef}
onPointerDown={monthSlide.onPointerDown}
onClickCapture={monthSlide.onClickCapture}
className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden overscroll-contain touch-none select-none"
>
<div className="grid shrink-0 grid-cols-7 border-b bg-muted/20 text-center text-xs font-medium text-muted-foreground">
{[1, 2, 3, 4, 5, 6, 7].map((wd) => (
<div key={wd} className="border-r py-1.5 last:border-r-0">
{translate(`schedule.weekday.${wd}`)}
</div>
))}
</div>
<div ref={monthSlide.viewportRef} className="relative min-h-0 flex-1 overflow-hidden">
<div
ref={monthSlide.gridTrackRef}
className="absolute inset-x-0 top-0 grid will-change-transform"
style={monthTrackStyle}
>
{monthTrackWeeks.map((row) => (
<div key={row.weekStart} className="grid min-h-0 grid-cols-7">
{row.days.map((dk) => {
const p = parseDateKey(dk);
const inMonth = p?.year === monthDominantParts.year && p?.month === monthDominantParts.month;
const isToday = dk === todayKey;
const dayEvents = occurrencesByDate.get(dk) ?? [];
const prevWeekParts = parseDateKey(addDaysToDateKey(dk, -7));
const isMonthTopEdge = Boolean(p && prevWeekParts && (p.month !== prevWeekParts.month || p.year !== prevWeekParts.year));
const shortMonth = p
? dateFormatters.monthShortFmt.format(new Date(Date.UTC(p.year, p.month - 1, 15)))
: "";
return (
<div
key={dk}
onClick={() => onCreateAtSlot(dk, 9 * 60, 10 * 60)}
className={cn(
"flex min-h-0 cursor-pointer flex-col gap-0.5 overflow-hidden border-r border-b p-1 transition-colors hover:bg-muted/20",
!inMonth && "bg-muted/15 text-muted-foreground",
isMonthTopEdge && "border-t border-t-border/90",
)}
>
<div className="flex items-center justify-between gap-1">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
jumpToDateKey(dk);
selectViewMode("day");
}}
className={cn(
"flex h-6 items-center justify-center rounded-full px-1.5 text-xs font-medium",
p?.day === 1 ? "gap-1" : "w-6 px-0",
isToday ? "bg-blue-600 text-white" : "hover:bg-accent",
)}
>
{p?.day === 1 ? (
<>
<span className="text-[10px] opacity-80">{shortMonth}</span>
<span>{p.day}</span>
</>
) : (
p?.day
)}
</button>
</div>
<div className="space-y-1">
{dayEvents.slice(0, 3).map((ev) => {
const st = STATUS_STYLE[ev.schedule.status] ?? STATUS_STYLE.waiting;
return (
<button
key={ev.id}
type="button"
onClick={(e) => {
e.stopPropagation();
setPopoverTimelineOpen(false);
setSelectedOccurrence(ev);
}}
className={cn(
"flex w-full items-center gap-1 truncate rounded border px-1.5 py-0.5 text-left text-[11px] font-medium",
st.card,
)}
>
<span className={cn("size-1.5 shrink-0 rounded-full", st.dot)} />
<span className="truncate">{ev.schedule.name}</span>
<span className="ml-auto shrink-0 font-mono text-[10px] opacity-75">
{ev.schedule.start_time.slice(0, 5)}
</span>
</button>
);
})}
{dayEvents.length > 3 ? (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
jumpToDateKey(dk);
selectViewMode("day");
}}
className="px-1 text-[11px] font-medium text-muted-foreground hover:text-foreground"
>
{translate("schedule.calendar.moreEvents", { count: dayEvents.length - 3 })}
</button>
) : null}
</div>
</div>
);
})}
</div>
))}
</div>
</div>
</div>
<MonthSwimlaneView
slide={monthSlide}
trackDateKeys={monthTrackDateKeys}
visibleStartIdx={monthBufferCols}
visibleCount={monthVisibleCols}
dominantMonth={{ year: monthDominantParts.year, month: monthDominantParts.month }}
monthShortFmt={dateFormatters.monthShortFmt}
todayKey={todayKey}
anchorDateKey={anchorDateKey}
schedules={visibleSchedules}
occurrences={occurrences}
selectedOccurrenceId={selectedOccurrence?.id ?? null}
onSelectOccurrence={(occ) => {
setPopoverTimelineOpen(false);
setSelectedOccurrence(occ);
}}
onSelectDay={(dk) => {
jumpToDateKey(dk);
selectViewMode("day");
}}
onCreateAtSlot={onCreateAtSlot}
/>
) : (
/* Week & Day Time Grid View: 64px time axis stays fixed while adjacent day columns glide smoothly */
<div
+1
View File
@@ -122,6 +122,7 @@ test("migrated pages reference existing keys and contain no hardcoded Chinese di
"app/(main)/system/settings/page.tsx",
"app/(main)/chat/page.tsx",
"app/(main)/function/schedules/page.tsx",
"app/(main)/function/schedules/_components/month-swimlane-view.tsx",
"components/remark-editor.tsx",
"app/(main)/function/tasks/page.tsx",
"components/task-template-controls.tsx",
+16
View File
@@ -291,6 +291,22 @@ export const scheduleMessages = {
"schedule.calendar.monthSchedulesCount": ["{{count}} 项", "{{count}}"],
"schedule.calendar.prevYear": ["上一年", "Previous year"],
"schedule.calendar.nextYear": ["下一年", "Next year"],
"schedule.month.laneTitle": ["计划泳道", "Schedule lanes"],
"schedule.month.laneHint": ["点日期看日视图 · 点色块看详情", "Click date for Day view · Click block for details"],
"schedule.month.cadenceOnce": ["一次性", "Once"],
"schedule.month.cadenceDaily": ["每日", "Daily"],
"schedule.month.cadenceWeekdays": ["工作日", "Weekdays"],
"schedule.month.cadenceWeekends": ["周末", "Weekends"],
"schedule.month.cadenceWeekly": ["每周", "Weekly"],
"schedule.month.runDays": ["{{count}} 天", "{{count}}d"],
"schedule.month.inactiveGroup": ["本月无排期计划({{count}})", "No runs this month ({{count}})"],
"schedule.month.empty": ["当前筛选条件下暂无计划任务", "No schedules match the current filters"],
"schedule.month.footerSummary": [
"本月 {{active}} 条活跃计划 · 共 {{runs}} 次排期",
"{{active}} active schedules · {{runs}} runs this month",
],
"schedule.month.createAtDay": ["在 {{date}} 新建计划", "Create schedule on {{date}}"],
"schedule.month.overnight": ["跨夜", "Overnight"],
"schedule.calendar.expandDetails": ["下拉或点击展开详情", "Pull down or click to expand details"],
"schedule.calendar.collapseDetails": ["上拉或点击收起详情", "Pull up or click to collapse details"],
"schedule.calendar.fullDetails": ["更多详情", "Full details"],