mirror of https://github.com/usememos/memos
refactor(web): improve ActivityCalendar maintainability and add Calendar page
- Extract shared utilities and constants to eliminate code duplication - Create dedicated Calendar page with year view and month grid - Add date filter navigation with bidirectional URL sync - Fix useTodayDate memoization bug causing stale date references - Standardize naming conventions (get vs generate functions) - Add comprehensive type exports and proper store encapsulation - Implement size variants for compact calendar display 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>pull/5354/head
parent
d14e66daf5
commit
1b3318f886
@ -0,0 +1,56 @@
|
||||
import { observer } from "mobx-react-lite";
|
||||
import { memo } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { instanceStore } from "@/store";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { CalendarCell } from "./CalendarCell";
|
||||
import { DEFAULT_CELL_SIZE, SMALL_CELL_SIZE } from "./constants";
|
||||
import { getTooltipText, useTodayDate, useWeekdayLabels } from "./shared";
|
||||
import type { CompactMonthCalendarProps } from "./types";
|
||||
import { useCalendarMatrix } from "./useCalendarMatrix";
|
||||
|
||||
export const CompactMonthCalendar = memo(
|
||||
observer((props: CompactMonthCalendarProps) => {
|
||||
const { month, data, maxCount, size = "default", onClick } = props;
|
||||
const t = useTranslate();
|
||||
|
||||
const weekStartDayOffset = instanceStore.state.generalSetting.weekStartDayOffset;
|
||||
|
||||
const today = useTodayDate();
|
||||
const weekDays = useWeekdayLabels();
|
||||
|
||||
const { weeks } = useCalendarMatrix({
|
||||
month,
|
||||
data,
|
||||
weekDays,
|
||||
weekStartDayOffset,
|
||||
today,
|
||||
selectedDate: "",
|
||||
});
|
||||
|
||||
const sizeConfig = size === "small" ? SMALL_CELL_SIZE : DEFAULT_CELL_SIZE;
|
||||
|
||||
return (
|
||||
<div className={cn("grid grid-cols-7", sizeConfig.gap)}>
|
||||
{weeks.map((week, weekIndex) =>
|
||||
week.days.map((day, dayIndex) => {
|
||||
const tooltipText = getTooltipText(day.count, day.date, t);
|
||||
|
||||
return (
|
||||
<CalendarCell
|
||||
key={`${weekIndex}-${dayIndex}-${day.date}`}
|
||||
day={day}
|
||||
maxCount={maxCount}
|
||||
tooltipText={tooltipText}
|
||||
onClick={onClick}
|
||||
size={size}
|
||||
/>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
CompactMonthCalendar.displayName = "CompactMonthCalendar";
|
||||
@ -0,0 +1,24 @@
|
||||
export const DAYS_IN_WEEK = 7;
|
||||
export const MONTHS_IN_YEAR = 12;
|
||||
export const WEEKEND_DAYS = [0, 6] as const;
|
||||
export const MIN_COUNT = 1;
|
||||
|
||||
export const INTENSITY_THRESHOLDS = {
|
||||
HIGH: 0.75,
|
||||
MEDIUM: 0.5,
|
||||
LOW: 0.25,
|
||||
MINIMAL: 0,
|
||||
} as const;
|
||||
|
||||
export const SMALL_CELL_SIZE = {
|
||||
font: "text-[10px]",
|
||||
dimensions: "max-w-6 max-h-6",
|
||||
borderRadius: "rounded-sm",
|
||||
gap: "gap-px",
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_CELL_SIZE = {
|
||||
font: "text-xs",
|
||||
borderRadius: "rounded",
|
||||
gap: "gap-0.5",
|
||||
} as const;
|
||||
@ -1 +1,21 @@
|
||||
export { ActivityCalendar as default } from "./ActivityCalendar";
|
||||
export { CalendarCell, type CalendarCellProps } from "./CalendarCell";
|
||||
export { CompactMonthCalendar } from "./CompactMonthCalendar";
|
||||
export * from "./constants";
|
||||
export { getTooltipText, type TranslateFunction, useTodayDate, useWeekdayLabels } from "./shared";
|
||||
export type {
|
||||
CalendarDayCell,
|
||||
CalendarDayRow,
|
||||
CalendarMatrixResult,
|
||||
CalendarSize,
|
||||
CompactMonthCalendarProps,
|
||||
} from "./types";
|
||||
export { type UseCalendarMatrixParams, useCalendarMatrix } from "./useCalendarMatrix";
|
||||
export {
|
||||
calculateYearMaxCount,
|
||||
filterDataByYear,
|
||||
generateMonthsForYear,
|
||||
getCellIntensityClass,
|
||||
getMonthLabel,
|
||||
hasActivityData,
|
||||
} from "./utils";
|
||||
|
||||
@ -0,0 +1,26 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
|
||||
export type TranslateFunction = ReturnType<typeof useTranslate>;
|
||||
|
||||
export const useWeekdayLabels = () => {
|
||||
const t = useTranslate();
|
||||
return useMemo(() => [t("days.sun"), t("days.mon"), t("days.tue"), t("days.wed"), t("days.thu"), t("days.fri"), t("days.sat")], [t]);
|
||||
};
|
||||
|
||||
export const useTodayDate = () => {
|
||||
return dayjs().format("YYYY-MM-DD");
|
||||
};
|
||||
|
||||
export const getTooltipText = (count: number, date: string, t: TranslateFunction): string => {
|
||||
if (count === 0) {
|
||||
return date;
|
||||
}
|
||||
|
||||
return t("memo.count-memos-in-date", {
|
||||
count,
|
||||
memos: count === 1 ? t("common.memo") : t("common.memos"),
|
||||
date,
|
||||
}).toLowerCase();
|
||||
};
|
||||
@ -1,13 +1,57 @@
|
||||
import dayjs from "dayjs";
|
||||
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
|
||||
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
|
||||
import { INTENSITY_THRESHOLDS, MIN_COUNT, MONTHS_IN_YEAR } from "./constants";
|
||||
import type { CalendarDayCell } from "./types";
|
||||
|
||||
dayjs.extend(isSameOrAfter);
|
||||
dayjs.extend(isSameOrBefore);
|
||||
|
||||
export const getCellIntensityClass = (day: CalendarDayCell, maxCount: number): string => {
|
||||
if (!day.isCurrentMonth || day.count === 0 || maxCount <= 0) {
|
||||
if (!day.isCurrentMonth || day.count === 0) {
|
||||
return "bg-transparent";
|
||||
}
|
||||
|
||||
const ratio = day.count / maxCount;
|
||||
if (ratio > 0.75) return "bg-primary text-primary-foreground border-primary";
|
||||
if (ratio > 0.5) return "bg-primary/80 text-primary-foreground border-primary/90";
|
||||
if (ratio > 0.25) return "bg-primary/60 text-primary-foreground border-primary/70";
|
||||
if (ratio > INTENSITY_THRESHOLDS.HIGH) return "bg-primary text-primary-foreground border-primary";
|
||||
if (ratio > INTENSITY_THRESHOLDS.MEDIUM) return "bg-primary/80 text-primary-foreground border-primary/90";
|
||||
if (ratio > INTENSITY_THRESHOLDS.LOW) return "bg-primary/60 text-primary-foreground border-primary/70";
|
||||
return "bg-primary/40 text-primary";
|
||||
};
|
||||
|
||||
export const generateMonthsForYear = (year: number): string[] => {
|
||||
return Array.from({ length: MONTHS_IN_YEAR }, (_, i) => dayjs(`${year}-01-01`).add(i, "month").format("YYYY-MM"));
|
||||
};
|
||||
|
||||
export const calculateYearMaxCount = (data: Record<string, number>): number => {
|
||||
let max = 0;
|
||||
for (const count of Object.values(data)) {
|
||||
max = Math.max(max, count);
|
||||
}
|
||||
return Math.max(max, MIN_COUNT);
|
||||
};
|
||||
|
||||
export const getMonthLabel = (month: string): string => {
|
||||
return dayjs(month).format("MMM YYYY");
|
||||
};
|
||||
|
||||
export const filterDataByYear = (data: Record<string, number>, year: number): Record<string, number> => {
|
||||
if (!data) return {};
|
||||
|
||||
const filtered: Record<string, number> = {};
|
||||
const yearStart = dayjs(`${year}-01-01`);
|
||||
const yearEnd = dayjs(`${year}-12-31`);
|
||||
|
||||
for (const [dateStr, count] of Object.entries(data)) {
|
||||
const date = dayjs(dateStr);
|
||||
if (date.isSameOrAfter(yearStart, "day") && date.isSameOrBefore(yearEnd, "day")) {
|
||||
filtered[dateStr] = count;
|
||||
}
|
||||
}
|
||||
|
||||
return filtered;
|
||||
};
|
||||
|
||||
export const hasActivityData = (data: Record<string, number>): boolean => {
|
||||
return Object.values(data).some((count) => count > 0);
|
||||
};
|
||||
|
||||
@ -0,0 +1,17 @@
|
||||
import { useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { stringifyFilters } from "@/store/memoFilter";
|
||||
|
||||
export const useDateFilterNavigation = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const navigateToDateFilter = useCallback(
|
||||
(date: string) => {
|
||||
const filterQuery = stringifyFilters([{ factor: "displayTime", value: date }]);
|
||||
navigate(`/?filter=${filterQuery}`);
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
return navigateToDateFilter;
|
||||
};
|
||||
@ -0,0 +1,145 @@
|
||||
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
|
||||
import { observer } from "mobx-react-lite";
|
||||
import { useMemo, useState } from "react";
|
||||
import {
|
||||
CompactMonthCalendar,
|
||||
calculateYearMaxCount,
|
||||
filterDataByYear,
|
||||
generateMonthsForYear,
|
||||
getMonthLabel,
|
||||
} from "@/components/ActivityCalendar";
|
||||
import MobileHeader from "@/components/MobileHeader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { useDateFilterNavigation } from "@/hooks";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
import { useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
|
||||
const MIN_YEAR = 2000;
|
||||
const MAX_YEAR = new Date().getFullYear() + 1;
|
||||
|
||||
const Calendar = observer(() => {
|
||||
const currentUser = useCurrentUser();
|
||||
const t = useTranslate();
|
||||
const navigateToDateFilter = useDateFilterNavigation();
|
||||
const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
|
||||
|
||||
const { statistics, loading } = useFilteredMemoStats({
|
||||
userName: currentUser?.name,
|
||||
});
|
||||
|
||||
const yearData = useMemo(() => filterDataByYear(statistics.activityStats, selectedYear), [statistics.activityStats, selectedYear]);
|
||||
|
||||
const months = useMemo(() => generateMonthsForYear(selectedYear), [selectedYear]);
|
||||
|
||||
const yearMaxCount = useMemo(() => calculateYearMaxCount(yearData), [yearData]);
|
||||
|
||||
const currentYear = useMemo(() => new Date().getFullYear(), []);
|
||||
const isCurrentYear = selectedYear === currentYear;
|
||||
|
||||
const handlePrevYear = () => {
|
||||
if (selectedYear > MIN_YEAR) {
|
||||
setSelectedYear(selectedYear - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNextYear = () => {
|
||||
if (selectedYear < MAX_YEAR) {
|
||||
setSelectedYear(selectedYear + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToday = () => {
|
||||
setSelectedYear(currentYear);
|
||||
};
|
||||
|
||||
const canGoPrev = selectedYear > MIN_YEAR;
|
||||
const canGoNext = selectedYear < MAX_YEAR;
|
||||
|
||||
return (
|
||||
<section className="relative w-full min-h-full flex flex-col justify-start items-center bg-background">
|
||||
<MobileHeader />
|
||||
<div className="relative w-full flex flex-col items-center px-3 sm:px-4 md:px-6 lg:px-8 pb-8">
|
||||
<div className="w-full max-w-7xl flex flex-col gap-3 sm:gap-4 py-3 sm:py-4">
|
||||
<div className="flex items-center justify-between pb-2">
|
||||
<h1 className="text-2xl sm:text-3xl md:text-4xl font-bold text-foreground tracking-tight leading-none">{selectedYear}</h1>
|
||||
|
||||
<div className="inline-flex items-center gap-2 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handlePrevYear}
|
||||
disabled={!canGoPrev}
|
||||
aria-label="Previous year"
|
||||
className="rounded-full hover:bg-accent/50 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={isCurrentYear ? "secondary" : "ghost"}
|
||||
onClick={handleToday}
|
||||
disabled={isCurrentYear}
|
||||
aria-label={t("common.today")}
|
||||
className={cn(
|
||||
"h-9 px-4 rounded-full font-medium text-sm transition-colors",
|
||||
isCurrentYear
|
||||
? "bg-accent text-accent-foreground cursor-default"
|
||||
: "hover:bg-accent/50 text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{t("common.today")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleNextYear}
|
||||
disabled={!canGoNext}
|
||||
aria-label="Next year"
|
||||
className="rounded-full hover:bg-accent/50 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="w-full flex items-center justify-center py-12">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
|
||||
<p className="text-sm text-muted-foreground">Loading calendar...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<TooltipProvider>
|
||||
<div className="w-full animate-fade-in">
|
||||
<div className="grid gap-2 sm:gap-2.5 md:gap-3 lg:gap-3 grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4">
|
||||
{months.map((month) => (
|
||||
<div
|
||||
key={month}
|
||||
className="flex flex-col gap-1 sm:gap-1.5 rounded-lg border bg-card p-1.5 sm:p-2 md:p-2.5 shadow-sm hover:shadow-md hover:border-border/60 transition-all duration-200"
|
||||
>
|
||||
<div className="text-xs font-semibold text-foreground text-center tracking-tight">{getMonthLabel(month)}</div>
|
||||
<CompactMonthCalendar
|
||||
month={month}
|
||||
data={yearData}
|
||||
maxCount={yearMaxCount}
|
||||
size="small"
|
||||
onClick={navigateToDateFilter}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
});
|
||||
|
||||
export default Calendar;
|
||||
Loading…
Reference in New Issue