refactor: reorganiza componentes compartilhados e caminhos do app

This commit is contained in:
Felipe Coutinho
2026-03-06 13:57:40 +00:00
parent f0497d5c5f
commit 069d0759c6
103 changed files with 225 additions and 622 deletions

View File

@@ -0,0 +1,56 @@
import Link from "next/link";
import { AnimatedThemeToggler } from "@/components/animated-theme-toggler";
import { Logo } from "@/components/logo";
import { NotificationBell } from "@/components/notificacoes/notification-bell";
import { RefreshPageButton } from "@/components/shared/refresh-page-button";
import type { DashboardNotificationsSnapshot } from "@/lib/dashboard/notifications";
import { NavMenu } from "./nav-menu";
import { NavbarUser } from "./navbar-user";
type AppNavbarProps = {
user: {
id: string;
name: string;
email: string;
image: string | null;
};
pagadorAvatarUrl: string | null;
preLancamentosCount?: number;
notificationsSnapshot: DashboardNotificationsSnapshot;
};
export function AppNavbar({
user,
pagadorAvatarUrl,
preLancamentosCount = 0,
notificationsSnapshot,
}: AppNavbarProps) {
return (
<header className="fixed top-0 left-0 right-0 z-50 h-16 shrink-0 flex items-center bg-card backdrop-blur-lg supports-backdrop-filter:bg-card/50">
<div className="w-full max-w-8xl mx-auto px-4 flex items-center gap-4 h-full">
{/* Logo */}
<Link href="/dashboard" className="shrink-0 mr-1">
<Logo variant="compact" />
</Link>
{/* Navigation */}
<NavMenu />
{/* Right-side actions */}
<div className="ml-auto flex items-center gap-2">
<NotificationBell
notifications={notificationsSnapshot.notifications}
totalCount={notificationsSnapshot.totalCount}
budgetNotifications={notificationsSnapshot.budgetNotifications}
preLancamentosCount={preLancamentosCount}
/>
<RefreshPageButton />
<AnimatedThemeToggler />
</div>
{/* User avatar */}
<NavbarUser user={user} pagadorAvatarUrl={pagadorAvatarUrl} />
</div>
</header>
);
}

View File

@@ -0,0 +1,60 @@
"use client";
import { usePathname } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils/ui";
import { NavLink } from "./nav-link";
type MobileLinkProps = {
href: string;
icon: React.ReactNode;
children: React.ReactNode;
onClick?: () => void;
badge?: number;
preservePeriod?: boolean;
};
export function MobileLink({
href,
icon,
children,
onClick,
badge,
preservePeriod,
}: MobileLinkProps) {
const pathname = usePathname();
const isActive =
href === "/dashboard"
? pathname === href
: pathname === href || pathname.startsWith(`${href}/`);
return (
<NavLink
href={href}
preservePeriod={preservePeriod}
onClick={onClick}
className={cn(
"flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors",
"text-muted-foreground hover:text-foreground hover:bg-accent",
isActive && "bg-primary/10 text-primary font-medium",
)}
>
<span className="text-muted-foreground shrink-0">{icon}</span>
<span className="flex-1">{children}</span>
{badge && badge > 0 ? (
<Badge variant="secondary" className="text-xs px-1.5 py-0">
{badge}
</Badge>
) : null}
</NavLink>
);
}
export function MobileSectionLabel({ label }: { label: string }) {
return (
<p className="mt-3 mb-1 px-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
{label}
</p>
);
}

View File

@@ -0,0 +1,36 @@
"use client";
import { Badge } from "@/components/ui/badge";
import type { NavItem } from "./nav-items";
import { NavLink } from "./nav-link";
type NavDropdownProps = {
items: NavItem[];
};
export function NavDropdown({ items }: NavDropdownProps) {
return (
<ul className="grid w-48 gap-0.5 p-2">
{items.map((item) => (
<li key={item.href}>
<NavLink
href={item.href}
preservePeriod={item.preservePeriod}
className="flex items-center gap-2.5 rounded-sm px-2 py-2 text-sm text-foreground hover:bg-accent transition-colors"
>
<span className="text-muted-foreground shrink-0">{item.icon}</span>
<span className="flex-1">{item.label}</span>
{item.badge && item.badge > 0 ? (
<Badge
variant="secondary"
className="text-[10px] px-1.5 py-0 h-4 min-w-4 ml-auto"
>
{item.badge}
</Badge>
) : null}
</NavLink>
</li>
))}
</ul>
);
}

View File

@@ -0,0 +1,127 @@
import {
RiArrowLeftRightLine,
RiAtLine,
RiBankCard2Line,
RiBankLine,
RiBarChart2Line,
RiCalendarEventLine,
RiFileChartLine,
RiGroupLine,
RiPriceTag3Line,
RiSecurePaymentLine,
RiSparklingLine,
RiStore2Line,
RiTodoLine,
} from "@remixicon/react";
export type NavItem = {
href: string;
label: string;
icon: React.ReactNode;
badge?: number;
preservePeriod?: boolean;
hideOnMobile?: boolean;
};
export type NavSection = {
label: string;
items: NavItem[];
};
export const NAV_SECTIONS: NavSection[] = [
{
label: "Lançamentos",
items: [
{
href: "/lancamentos",
label: "lançamentos",
icon: <RiArrowLeftRightLine className="size-4" />,
preservePeriod: true,
},
{
href: "/pre-lancamentos",
label: "pré-lançamentos",
icon: <RiAtLine className="size-4" />,
},
{
href: "/calendario",
label: "calendário",
icon: <RiCalendarEventLine className="size-4" />,
hideOnMobile: true,
},
],
},
{
label: "Finanças",
items: [
{
href: "/cartoes",
label: "cartões",
icon: <RiBankCard2Line className="size-4" />,
},
{
href: "/contas",
label: "contas",
icon: <RiBankLine className="size-4" />,
},
{
href: "/orcamentos",
label: "orçamentos",
icon: <RiBarChart2Line className="size-4" />,
preservePeriod: true,
},
],
},
{
label: "Organização",
items: [
{
href: "/pagadores",
label: "pagadores",
icon: <RiGroupLine className="size-4" />,
},
{
href: "/categorias",
label: "categorias",
icon: <RiPriceTag3Line className="size-4" />,
},
{
href: "/anotacoes",
label: "anotações",
icon: <RiTodoLine className="size-4" />,
},
],
},
{
label: "Relatórios",
items: [
{
href: "/insights",
label: "insights",
icon: <RiSparklingLine className="size-4" />,
preservePeriod: true,
},
{
href: "/relatorios/tendencias",
label: "tendências",
icon: <RiFileChartLine className="size-4" />,
},
{
href: "/relatorios/uso-cartoes",
label: "uso de cartões",
icon: <RiBankCard2Line className="size-4" />,
preservePeriod: true,
},
{
href: "/relatorios/analise-parcelas",
label: "análise de parcelas",
icon: <RiSecurePaymentLine className="size-4" />,
},
{
href: "/relatorios/estabelecimentos",
label: "estabelecimentos",
icon: <RiStore2Line className="size-4" />,
},
],
},
];

View File

@@ -0,0 +1,30 @@
"use client";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useMemo } from "react";
const PERIOD_PARAM = "periodo";
type NavLinkProps = Omit<React.ComponentProps<typeof Link>, "href"> & {
href: string;
preservePeriod?: boolean;
};
export function NavLink({
href,
preservePeriod = false,
...props
}: NavLinkProps) {
const searchParams = useSearchParams();
const resolvedHref = useMemo(() => {
if (!preservePeriod) return href;
const periodo = searchParams.get(PERIOD_PARAM);
if (!periodo) return href;
const separator = href.includes("?") ? "&" : "?";
return `${href}${separator}${PERIOD_PARAM}=${encodeURIComponent(periodo)}`;
}, [href, preservePeriod, searchParams]);
return <Link href={resolvedHref} {...props} />;
}

View File

@@ -0,0 +1,131 @@
"use client";
import { RiDashboardLine, RiMenuLine } from "@remixicon/react";
import { useState } from "react";
import { CalculatorDialogContent } from "@/components/calculadora/calculator-dialog";
import { Button } from "@/components/ui/button";
import { Dialog } from "@/components/ui/dialog";
import {
NavigationMenu,
NavigationMenuContent,
NavigationMenuItem,
NavigationMenuList,
NavigationMenuTrigger,
} from "@/components/ui/navigation-menu";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { MobileLink, MobileSectionLabel } from "./mobile-link";
import { NavDropdown } from "./nav-dropdown";
import { NAV_SECTIONS } from "./nav-items";
import { NavPill } from "./nav-pill";
import { triggerClass } from "./nav-styles";
import { MobileTools, NavToolsDropdown } from "./nav-tools";
export function NavMenu() {
const [sheetOpen, setSheetOpen] = useState(false);
const [calculatorOpen, setCalculatorOpen] = useState(false);
const close = () => setSheetOpen(false);
const openCalculator = () => setCalculatorOpen(true);
return (
<>
{/* Desktop */}
<nav className="hidden md:flex items-center justify-center flex-1">
<NavigationMenu viewport={false}>
<NavigationMenuList className="gap-0">
<NavigationMenuItem>
<NavPill href="/dashboard" preservePeriod>
Dashboard
</NavPill>
</NavigationMenuItem>
{NAV_SECTIONS.map((section) => (
<NavigationMenuItem key={section.label}>
<NavigationMenuTrigger className={triggerClass}>
{section.label}
</NavigationMenuTrigger>
<NavigationMenuContent>
<NavDropdown items={section.items} />
</NavigationMenuContent>
</NavigationMenuItem>
))}
<NavigationMenuItem>
<NavigationMenuTrigger className={triggerClass}>
Ferramentas
</NavigationMenuTrigger>
<NavigationMenuContent>
<NavToolsDropdown onOpenCalculator={openCalculator} />
</NavigationMenuContent>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
</nav>
{/* Mobile - order-[-1] places hamburger before logo visually */}
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
<SheetTrigger asChild>
<Button
variant="ghost"
size="icon"
className="-order-1 md:hidden text-foreground hover:bg-foreground/10 hover:text-foreground"
>
<RiMenuLine className="size-5" />
<span className="sr-only">Abrir menu</span>
</Button>
</SheetTrigger>
<SheetContent side="left" className="w-72 p-0">
<SheetHeader className="p-4 border-b">
<SheetTitle>Menu</SheetTitle>
</SheetHeader>
<nav className="p-3 overflow-y-auto">
<MobileLink
href="/dashboard"
icon={<RiDashboardLine className="size-4" />}
onClick={close}
preservePeriod
>
dashboard
</MobileLink>
{NAV_SECTIONS.map((section) => {
const mobileItems = section.items.filter(
(item) => !item.hideOnMobile,
);
if (mobileItems.length === 0) return null;
return (
<div key={section.label}>
<MobileSectionLabel label={section.label} />
{mobileItems.map((item) => (
<MobileLink
key={item.href}
href={item.href}
icon={item.icon}
onClick={close}
badge={item.badge}
preservePeriod={item.preservePeriod}
>
{item.label}
</MobileLink>
))}
</div>
);
})}
<MobileSectionLabel label="Ferramentas" />
<MobileTools onClose={close} onOpenCalculator={openCalculator} />
</nav>
</SheetContent>
</Sheet>
<Dialog open={calculatorOpen} onOpenChange={setCalculatorOpen}>
<CalculatorDialogContent open={calculatorOpen} />
</Dialog>
</>
);
}

View File

@@ -0,0 +1,31 @@
"use client";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils/ui";
import { NavLink } from "./nav-link";
import { linkActive, linkBase, linkIdle } from "./nav-styles";
type NavPillProps = {
href: string;
preservePeriod?: boolean;
children: React.ReactNode;
};
export function NavPill({ href, preservePeriod, children }: NavPillProps) {
const pathname = usePathname();
const isActive =
href === "/dashboard"
? pathname === href
: pathname === href || pathname.startsWith(`${href}/`);
return (
<NavLink
href={href}
preservePeriod={preservePeriod}
className={cn(linkBase, isActive ? linkActive : linkIdle)}
>
{children}
</NavLink>
);
}

View File

@@ -0,0 +1,30 @@
// Base para links diretos e triggers — pill arredondado
export const linkBase =
"inline-flex h-8 items-center justify-center rounded-full px-3 text-sm font-medium transition-all lowercase";
// Estado inativo: muted, hover suave sem underline
export const linkIdle =
"text-muted-foreground hover:text-foreground hover:bg-accent";
// Estado ativo: pill com cor primária
export const linkActive = "bg-primary/10 text-primary";
// Trigger do NavigationMenu — espelha linkBase + linkIdle, remove estilos padrão
export const triggerClass = [
"h-8!",
"rounded-full!",
"px-3!",
"py-0!",
"text-sm!",
"font-medium!",
"bg-transparent!",
"text-muted-foreground!",
"hover:text-foreground!",
"hover:bg-accent!",
"focus:text-foreground!",
"focus:bg-accent!",
"data-[state=open]:text-foreground!",
"data-[state=open]:bg-accent!",
"shadow-none!",
"lowercase!",
].join(" ");

View File

@@ -0,0 +1,106 @@
"use client";
import { RiCalculatorLine, RiEyeLine, RiEyeOffLine } from "@remixicon/react";
import { usePrivacyMode } from "@/components/privacy-provider";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils/ui";
const itemClass =
"flex w-full items-center gap-2.5 rounded-sm px-2 py-2 text-sm text-foreground hover:bg-accent transition-colors cursor-pointer";
type NavToolsDropdownProps = {
onOpenCalculator: () => void;
};
export function NavToolsDropdown({ onOpenCalculator }: NavToolsDropdownProps) {
const { privacyMode, toggle } = usePrivacyMode();
return (
<ul className="grid w-52 gap-0.5 p-2">
<li>
<button
type="button"
className={cn(itemClass)}
onClick={onOpenCalculator}
>
<span className="text-muted-foreground shrink-0">
<RiCalculatorLine className="size-4" />
</span>
<span className="flex-1 text-left">calculadora</span>
</button>
</li>
<li>
<button type="button" onClick={toggle} className={cn(itemClass)}>
<span className="text-muted-foreground shrink-0">
{privacyMode ? (
<RiEyeOffLine className="size-4" />
) : (
<RiEyeLine className="size-4" />
)}
</span>
<span className="flex-1 text-left">privacidade</span>
{privacyMode && (
<Badge
variant="secondary"
className="text-[10px] px-1.5 py-0 h-4 text-success"
>
Ativo
</Badge>
)}
</button>
</li>
</ul>
);
}
type MobileToolsProps = {
onClose: () => void;
onOpenCalculator: () => void;
};
export function MobileTools({ onClose, onOpenCalculator }: MobileToolsProps) {
const { privacyMode, toggle } = usePrivacyMode();
return (
<>
<button
type="button"
onClick={() => {
onClose();
onOpenCalculator();
}}
className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors text-muted-foreground hover:text-foreground hover:bg-accent"
>
<span className="text-muted-foreground shrink-0">
<RiCalculatorLine className="size-4" />
</span>
<span className="flex-1 text-left">calculadora</span>
</button>
<button
type="button"
onClick={() => {
toggle();
onClose();
}}
className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors text-muted-foreground hover:text-foreground hover:bg-accent"
>
<span className="text-muted-foreground shrink-0">
{privacyMode ? (
<RiEyeOffLine className="size-4" />
) : (
<RiEyeLine className="size-4" />
)}
</span>
<span className="flex-1 text-left">privacidade</span>
{privacyMode && (
<Badge
variant="secondary"
className="text-[10px] px-1.5 py-0 h-4 text-success"
>
Ativo
</Badge>
)}
</button>
</>
);
}

View File

@@ -0,0 +1,151 @@
"use client";
import {
RiHistoryLine,
RiLogoutCircleLine,
RiMessageLine,
RiSettings2Line,
} from "@remixicon/react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { FeedbackDialogBody } from "@/components/feedback/feedback-dialog";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogTrigger } from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Spinner } from "@/components/ui/spinner";
import { authClient } from "@/lib/auth/client";
import { getAvatarSrc } from "@/lib/pagadores/utils";
import { cn } from "@/lib/utils/ui";
import { version } from "@/package.json";
const itemClass =
"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-sm transition-colors hover:bg-accent";
type NavbarUserProps = {
user: {
id: string;
name: string;
email: string;
image: string | null;
};
pagadorAvatarUrl: string | null;
};
export function NavbarUser({ user, pagadorAvatarUrl }: NavbarUserProps) {
const router = useRouter();
const [logoutLoading, setLogoutLoading] = useState(false);
const [feedbackOpen, setFeedbackOpen] = useState(false);
const avatarSrc = useMemo(() => {
if (pagadorAvatarUrl) return getAvatarSrc(pagadorAvatarUrl);
if (user.image) return user.image;
return getAvatarSrc(null);
}, [user.image, pagadorAvatarUrl]);
async function handleLogout() {
await authClient.signOut({
fetchOptions: {
onSuccess: () => router.push("/login"),
onRequest: () => setLogoutLoading(true),
onResponse: () => setLogoutLoading(false),
},
});
}
return (
<Dialog open={feedbackOpen} onOpenChange={setFeedbackOpen}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="relative flex size-9 items-center justify-center overflow-hidden rounded-full border-background bg-background shadow-lg"
aria-label="Menu do usuário"
>
<Image
src={avatarSrc}
alt={`Avatar de ${user.name}`}
width={40}
height={40}
className="size-10 rounded-full object-cover"
/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-60 p-2" sideOffset={10}>
<DropdownMenuLabel className="flex items-center gap-3 px-2 py-2">
<Image
src={avatarSrc}
alt={user.name}
width={36}
height={36}
className="size-9 rounded-full object-cover shrink-0"
/>
<div className="flex flex-col min-w-0">
<span className="text-sm font-medium truncate">{user.name}</span>
<span className="text-xs text-muted-foreground truncate">
{user.email}
</span>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<div className="flex flex-col gap-0.5 py-1">
<Link href="/ajustes" className={cn(itemClass, "text-foreground")}>
<RiSettings2Line className="size-4 text-muted-foreground shrink-0" />
Ajustes
</Link>
<Link
href="/changelog"
className={cn(itemClass, "text-foreground")}
>
<RiHistoryLine className="size-4 text-muted-foreground shrink-0" />
<span className="flex-1">Changelog</span>
<Badge variant="secondary">v{version}</Badge>
</Link>
<DialogTrigger asChild>
<button
type="button"
className={cn(itemClass, "text-foreground")}
>
<RiMessageLine className="size-4 text-muted-foreground shrink-0" />
Enviar Feedback
</button>
</DialogTrigger>
</div>
<DropdownMenuSeparator />
<div className="py-1">
<button
type="button"
onClick={handleLogout}
disabled={logoutLoading}
aria-busy={logoutLoading}
className={cn(
itemClass,
"text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-60",
)}
>
{logoutLoading ? (
<Spinner className="size-4 shrink-0" />
) : (
<RiLogoutCircleLine className="size-4 shrink-0" />
)}
{logoutLoading ? "Saindo..." : "Sair"}
</button>
</div>
</DropdownMenuContent>
</DropdownMenu>
<FeedbackDialogBody onClose={() => setFeedbackOpen(false)} />
</Dialog>
);
}

View File

@@ -0,0 +1,83 @@
"use client";
import * as React from "react";
import { Logo } from "@/components/logo";
import { NavMain } from "@/components/navigation/sidebar/nav-main";
import { NavSecondary } from "@/components/navigation/sidebar/nav-secondary";
import { NavUser } from "@/components/navigation/sidebar/nav-user";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { createSidebarNavData, type PagadorLike } from "./nav-link";
type AppUser = {
id: string;
name: string;
email: string;
image: string | null;
};
interface AppSidebarProps extends React.ComponentProps<typeof Sidebar> {
user: AppUser;
pagadorAvatarUrl: string | null;
pagadores: PagadorLike[];
preLancamentosCount?: number;
}
export function AppSidebar({
user,
pagadorAvatarUrl,
pagadores,
preLancamentosCount = 0,
...props
}: AppSidebarProps) {
if (!user) {
throw new Error("AppSidebar requires a user but received undefined.");
}
const navigation = React.useMemo(
() => createSidebarNavData({ pagadores, preLancamentosCount }),
[pagadores, preLancamentosCount],
);
return (
<Sidebar collapsible="icon" {...props}>
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
asChild
className="data-[slot=sidebar-menu-button]:px-1.5! hover:bg-transparent active:bg-transparent pt-8 py-6 justify-center hover:scale-120 scale-110 transition-all duration-200"
>
<a href="/dashboard">
<LogoContent />
</a>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<NavMain sections={navigation.navMain} />
<NavSecondary items={navigation.navSecondary} className="mt-auto" />
</SidebarContent>
<SidebarFooter>
<NavUser user={user} pagadorAvatarUrl={pagadorAvatarUrl} />
</SidebarFooter>
</Sidebar>
);
}
function LogoContent() {
const { state } = useSidebar();
const isCollapsed = state === "collapsed";
return (
<Logo variant={isCollapsed ? "small" : "full"} showVersion={!isCollapsed} />
);
}

View File

@@ -0,0 +1,185 @@
import {
type RemixiconComponentType,
RiArrowLeftRightLine,
RiAtLine,
RiBankCard2Line,
RiBankLine,
RiCalendarEventLine,
RiDashboardLine,
RiFileChartLine,
RiFundsLine,
RiGroupLine,
RiPriceTag3Line,
RiSecurePaymentLine,
RiSettings2Line,
RiSparklingLine,
RiTodoLine,
} from "@remixicon/react";
export type SidebarSubItem = {
title: string;
url: string;
avatarUrl?: string | null;
isShared?: boolean;
key?: string;
icon?: RemixiconComponentType;
badge?: number;
};
export type SidebarItem = {
title: string;
url: string;
icon: RemixiconComponentType;
isActive?: boolean;
items?: SidebarSubItem[];
};
export type SidebarSection = {
title: string;
items: SidebarItem[];
};
export type SidebarNavData = {
navMain: SidebarSection[];
navSecondary: {
title: string;
url: string;
icon: RemixiconComponentType;
}[];
};
export interface PagadorLike {
id: string;
name: string | null;
avatarUrl: string | null;
canEdit?: boolean;
}
export interface SidebarNavOptions {
pagadores: PagadorLike[];
preLancamentosCount?: number;
}
export function createSidebarNavData(
options: SidebarNavOptions,
): SidebarNavData {
const { pagadores, preLancamentosCount = 0 } = options;
const pagadorItems = pagadores
.map((pagador) => ({
title: pagador.name?.trim().length
? pagador.name.trim()
: "Pagador sem nome",
url: `/pagadores/${pagador.id}`,
key: pagador.canEdit ? pagador.id : `${pagador.id}-shared`,
isShared: !pagador.canEdit,
avatarUrl: pagador.avatarUrl,
}))
.sort((a, b) =>
a.title.localeCompare(b.title, "pt-BR", { sensitivity: "base" }),
);
const pagadorItemsWithHistory: SidebarSubItem[] = pagadorItems;
return {
navMain: [
{
title: "Gestão Financeira",
items: [
{
title: "Dashboard",
url: "/dashboard",
icon: RiDashboardLine,
},
{
title: "Lançamentos",
url: "/lancamentos",
icon: RiArrowLeftRightLine,
items: [
{
title: "Pré-Lançamentos",
url: "/pre-lancamentos",
key: "pre-lancamentos",
icon: RiAtLine,
badge:
preLancamentosCount > 0 ? preLancamentosCount : undefined,
},
],
},
{
title: "Calendário",
url: "/calendario",
icon: RiCalendarEventLine,
},
{
title: "Cartões",
url: "/cartoes",
icon: RiBankCard2Line,
},
{
title: "Contas",
url: "/contas",
icon: RiBankLine,
},
{
title: "Orçamentos",
url: "/orcamentos",
icon: RiFundsLine,
},
],
},
{
title: "Organização",
items: [
{
title: "Pagadores",
url: "/pagadores",
icon: RiGroupLine,
items: pagadorItemsWithHistory,
},
{
title: "Categorias",
url: "/categorias",
icon: RiPriceTag3Line,
},
{
title: "Anotações",
url: "/anotacoes",
icon: RiTodoLine,
},
],
},
{
title: "Análise",
items: [
{
title: "Insights",
url: "/insights",
icon: RiSparklingLine,
},
{
title: "Tendências",
url: "/relatorios/tendencias",
icon: RiFileChartLine,
},
{
title: "Uso de Cartões",
url: "/relatorios/uso-cartoes",
icon: RiBankCard2Line,
},
{
title: "Análise de Parcelas",
url: "/relatorios/analise-parcelas",
icon: RiSecurePaymentLine,
},
],
},
],
navSecondary: [
{
title: "Ajustes",
url: "/ajustes",
icon: RiSettings2Line,
},
],
};
}

View File

@@ -0,0 +1,212 @@
"use client";
import {
type RemixiconComponentType,
RiArrowRightSLine,
RiUserSharedLine,
} from "@remixicon/react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
} from "@/components/ui/sidebar";
import { getAvatarSrc } from "@/lib/pagadores/utils";
type NavItem = {
title: string;
url: string;
icon: RemixiconComponentType;
isActive?: boolean;
items?: {
title: string;
url: string;
avatarUrl?: string | null;
isShared?: boolean;
key?: string;
icon?: RemixiconComponentType;
badge?: number;
}[];
};
type NavSection = {
title: string;
items: NavItem[];
};
const MONTH_PERIOD_PARAM = "periodo";
const PERIOD_AWARE_PATHS = new Set([
"/dashboard",
"/lancamentos",
"/orcamentos",
]);
export function NavMain({ sections }: { sections: NavSection[] }) {
const pathname = usePathname();
const searchParams = useSearchParams();
const periodParam = searchParams.get(MONTH_PERIOD_PARAM);
const normalizedPathname =
pathname.endsWith("/") && pathname !== "/"
? pathname.slice(0, -1)
: pathname;
const isLinkActive = (url: string) => {
const normalizedUrl =
url.endsWith("/") && url !== "/" ? url.slice(0, -1) : url;
// Verifica se é exatamente igual ou se o pathname começa com a URL
return (
normalizedPathname === normalizedUrl ||
normalizedPathname.startsWith(`${normalizedUrl}/`)
);
};
const buildHrefWithPeriod = (url: string) => {
if (!periodParam) {
return url;
}
const [rawPathname, existingSearch = ""] = url.split("?");
const normalizedRawPathname =
rawPathname.endsWith("/") && rawPathname !== "/"
? rawPathname.slice(0, -1)
: rawPathname;
if (!PERIOD_AWARE_PATHS.has(normalizedRawPathname)) {
return url;
}
const params = new URLSearchParams(existingSearch);
params.set(MONTH_PERIOD_PARAM, periodParam);
const queryString = params.toString();
return queryString
? `${normalizedRawPathname}?${queryString}`
: normalizedRawPathname;
};
const activeLinkClasses =
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-dark! hover:text-primary!";
return (
<>
{sections.map((section, index) => (
<SidebarGroup key={section.title}>
<SidebarGroupLabel className="text-xs text-muted-foreground/60">
{section.title}
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{section.items.map((item) => {
const itemIsActive = isLinkActive(item.url);
return (
<Collapsible key={item.title} asChild>
<SidebarMenuItem>
<SidebarMenuButton
asChild
tooltip={item.title}
isActive={itemIsActive}
className={itemIsActive ? activeLinkClasses : ""}
>
<Link prefetch href={buildHrefWithPeriod(item.url)}>
<item.icon className="size-4" />
{item.title}
</Link>
</SidebarMenuButton>
{item.items?.length ? (
<>
<CollapsibleTrigger asChild>
<SidebarMenuAction className="data-[state=open]:rotate-90 px-2 trasition-transform duration-200">
<RiArrowRightSLine className="text-primary" />
<span className="sr-only">Toggle</span>
</SidebarMenuAction>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub>
{item.items?.map((subItem) => {
const subItemIsActive = isLinkActive(
subItem.url,
);
const avatarSrc = getAvatarSrc(
subItem.avatarUrl,
);
const initial =
subItem.title.charAt(0).toUpperCase() || "?";
return (
<SidebarMenuSubItem
key={subItem.key ?? subItem.title}
>
<SidebarMenuSubButton
asChild
isActive={subItemIsActive}
className={
subItemIsActive ? activeLinkClasses : ""
}
>
<Link
prefetch
href={buildHrefWithPeriod(subItem.url)}
className="flex items-center gap-2"
>
{subItem.icon ? (
<subItem.icon className="size-4" />
) : subItem.avatarUrl !== undefined ? (
<Avatar className="size-5 border border-border/60 bg-background">
<AvatarImage
src={avatarSrc}
alt={`Avatar de ${subItem.title}`}
/>
<AvatarFallback className="text-xs font-medium uppercase">
{initial}
</AvatarFallback>
</Avatar>
) : null}
<span>{subItem.title}</span>
{subItem.badge ? (
<Badge
variant="destructive"
className="ml-auto h-5 min-w-5 px-1.5 text-xs"
>
{subItem.badge}
</Badge>
) : null}
{subItem.isShared ? (
<RiUserSharedLine className="size-3.5 text-muted-foreground" />
) : null}
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
</SidebarMenuSub>
</CollapsibleContent>
</>
) : null}
</SidebarMenuItem>
</Collapsible>
);
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
))}
</>
);
}

View File

@@ -0,0 +1,74 @@
"use client";
import type { RemixiconComponentType } from "@remixicon/react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import * as React from "react";
import {
SidebarGroup,
SidebarGroupContent,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
export function NavSecondary({
items,
...props
}: {
items: {
title: string;
url: string;
icon: RemixiconComponentType;
}[];
} & React.ComponentPropsWithoutRef<typeof SidebarGroup>) {
const pathname = usePathname();
const isLinkActive = React.useCallback(
(url: string) => {
const normalizedPathname =
pathname.endsWith("/") && pathname !== "/"
? pathname.slice(0, -1)
: pathname;
const normalizedUrl =
url.endsWith("/") && url !== "/" ? url.slice(0, -1) : url;
// Verifica se é exatamente igual ou se o pathname começa com a URL
return (
normalizedPathname === normalizedUrl ||
normalizedPathname.startsWith(`${normalizedUrl}/`)
);
},
[pathname],
);
return (
<SidebarGroup {...props}>
<SidebarGroupContent>
<SidebarMenu>
{items.map((item) => {
const itemIsActive = isLinkActive(item.url);
return (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
isActive={itemIsActive}
className={
itemIsActive
? "data-[active=true]:bg-sidebar-accent data-[active=true]:text-dark! hover:text-primary!"
: ""
}
>
<Link prefetch href={item.url}>
<item.icon className={"h-4 w-4"} />
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
);
}

View File

@@ -0,0 +1,62 @@
"use client";
import Image from "next/image";
import { useMemo } from "react";
import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { getAvatarSrc } from "@/lib/pagadores/utils";
type NavUserProps = {
user: {
id: string;
name: string;
email: string;
image: string | null;
};
pagadorAvatarUrl: string | null;
};
export function NavUser({ user, pagadorAvatarUrl }: NavUserProps) {
useSidebar();
const avatarSrc = useMemo(() => {
// Priorizar o avatar do pagador admin quando disponível
if (pagadorAvatarUrl) {
return getAvatarSrc(pagadorAvatarUrl);
}
// Fallback para a imagem do usuário (Google, etc)
if (user.image) {
return user.image;
}
return getAvatarSrc(null);
}, [user.image, pagadorAvatarUrl]);
return (
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="lg"
className="data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground "
>
<Image
src={avatarSrc}
alt={user.name}
width={32}
height={32}
className="size-8 shrink-0 rounded-full object-cover"
/>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{user.name}</span>
<span className="text-muted-foreground truncate text-xs">
{user.email}
</span>
</div>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
);
}