refactor hooks organization and month picker

This commit is contained in:
Felipe Coutinho
2026-03-06 16:39:49 +00:00
parent 9a5e9161db
commit ad0df4ea81
22 changed files with 239 additions and 239 deletions

View File

@@ -3,61 +3,37 @@
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useTransition } from "react";
import { Card } from "@/components/ui/card";
import { useMonthPeriod } from "@/hooks/use-month-period";
import { getNextPeriod, getPreviousPeriod } from "@/lib/utils/period";
import LoadingSpinner from "./loading-spinner";
import NavigationButton from "./nav-button";
import ReturnButton from "./return-button";
import { useMonthPeriod } from "./use-month-period";
export default function MonthNavigation() {
const {
monthNames,
currentMonth,
currentYear,
defaultMonth,
defaultYear,
buildHref,
} = useMonthPeriod();
const { period, currentMonth, currentYear, defaultPeriod, buildHref } =
useMonthPeriod();
const router = useRouter();
const [isPending, startTransition] = useTransition();
const currentMonthLabel = useMemo(
() => currentMonth.charAt(0).toUpperCase() + currentMonth.slice(1),
[currentMonth],
() =>
`${currentMonth.charAt(0).toUpperCase()}${currentMonth.slice(1)} ${currentYear}`,
[currentMonth, currentYear],
);
const currentMonthIndex = useMemo(
() => monthNames.indexOf(currentMonth),
[monthNames, currentMonth],
const prevTarget = useMemo(
() => buildHref(getPreviousPeriod(period)),
[buildHref, period],
);
const nextTarget = useMemo(
() => buildHref(getNextPeriod(period)),
[buildHref, period],
);
const prevTarget = useMemo(() => {
let idx = currentMonthIndex - 1;
let year = currentYear;
if (idx < 0) {
idx = monthNames.length - 1;
year = (parseInt(currentYear, 10) - 1).toString();
}
return buildHref(monthNames[idx], year);
}, [currentMonthIndex, currentYear, monthNames, buildHref]);
const nextTarget = useMemo(() => {
let idx = currentMonthIndex + 1;
let year = currentYear;
if (idx >= monthNames.length) {
idx = 0;
year = (parseInt(currentYear, 10) + 1).toString();
}
return buildHref(monthNames[idx], year);
}, [currentMonthIndex, currentYear, monthNames, buildHref]);
const returnTarget = useMemo(
() => buildHref(defaultMonth, defaultYear),
[buildHref, defaultMonth, defaultYear],
() => buildHref(defaultPeriod),
[buildHref, defaultPeriod],
);
const isDifferentFromCurrent =
currentMonth !== defaultMonth || currentYear !== defaultYear.toString();
const isDifferentFromCurrent = period !== defaultPeriod;
// Prefetch otimizado: apenas meses adjacentes (M-1, M+1) e mês atual
// Isso melhora a performance da navegação sem sobrecarregar o cliente
@@ -91,10 +67,9 @@ export default function MonthNavigation() {
<div
className="mx-1 space-x-1 capitalize font-semibold"
aria-current={!isDifferentFromCurrent ? "date" : undefined}
aria-label={`Período selecionado: ${currentMonthLabel} de ${currentYear}`}
aria-label={`Período selecionado: ${currentMonthLabel}`}
>
<span>{currentMonthLabel}</span>
<span>{currentYear}</span>
</div>
{isPending && <LoadingSpinner />}

View File

@@ -0,0 +1,90 @@
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback, useMemo } from "react";
import {
formatPeriod,
formatPeriodForUrl,
formatPeriodParam,
MONTH_NAMES,
parsePeriodParam,
} from "@/lib/utils/period";
const PERIOD_PARAM = "periodo";
export function useMonthPeriod() {
const searchParams = useSearchParams();
const pathname = usePathname();
const router = useRouter();
const periodFromParams = searchParams.get(PERIOD_PARAM);
const referenceDate = useMemo(() => new Date(), []);
const defaultPeriod = useMemo(
() =>
formatPeriod(referenceDate.getFullYear(), referenceDate.getMonth() + 1),
[referenceDate],
);
const { period, monthName, year } = useMemo(
() => parsePeriodParam(periodFromParams, referenceDate),
[periodFromParams, referenceDate],
);
const defaultMonth = useMemo(
() => MONTH_NAMES[referenceDate.getMonth()] ?? "",
[referenceDate],
);
const defaultYear = useMemo(
() => referenceDate.getFullYear().toString(),
[referenceDate],
);
const buildHref = useCallback(
(targetPeriod: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set(PERIOD_PARAM, formatPeriodForUrl(targetPeriod));
return `${pathname}?${params.toString()}`;
},
[pathname, searchParams],
);
const buildHrefFromMonth = useCallback(
(month: string, nextYear: string | number) => {
const parsedYear = Number.parseInt(String(nextYear).trim(), 10);
if (Number.isNaN(parsedYear)) {
return buildHref(defaultPeriod);
}
const param = formatPeriodParam(month, parsedYear);
const parsed = parsePeriodParam(param, referenceDate);
return buildHref(parsed.period);
},
[buildHref, defaultPeriod, referenceDate],
);
const replacePeriod = useCallback(
(targetPeriod: string) => {
if (!targetPeriod) {
return;
}
router.replace(buildHref(targetPeriod), { scroll: false });
},
[buildHref, router],
);
return {
pathname,
period,
currentMonth: monthName,
currentYear: year.toString(),
defaultPeriod,
defaultMonth,
defaultYear,
buildHref,
buildHrefFromMonth,
replacePeriod,
};
}
export { PERIOD_PARAM as MONTH_PERIOD_PARAM };