'use client'; import React, { ReactElement } from 'react'; import { Menu, Avatar, Text, Group, UnstyledButton, rem, Divider, Box, } from '@mantine/core'; import { IconLogout, IconSettings, IconUser, IconChevronDown, } from '@tabler/icons-react'; import { UserButtonProps, UserButtonMenuItemProps, UserButtonLinkProps } from './UserButton.types'; import { useAuth } from '../../hooks/useAuth'; import { useRouter } from 'next/navigation'; import classes from './UserButton.module.css'; // Sub-components function MenuItems({ children }: { children: ReactNode }) { return <>{children}; } function Link({ children, href, icon, onClick, color, disabled }: UserButtonLinkProps) { const router = useRouter(); const handleClick = () => { if (onClick) { onClick(); } else { router.push(href); } }; return ( {children} ); } function Action({ children, onClick, icon, color, disabled }: UserButtonMenuItemProps) { return ( {children} ); } // Main component export function UserButton({ afterSignOutUrl = '/', afterMultiSessionSingleSignOutUrl, afterSwitchSessionUrl, appearance, showName = false, children, className, style, }: UserButtonProps) { const { user, signOut } = useAuth(); const router = useRouter(); if (!user) { return null; } const handleSignOut = async () => { await signOut(); router.push(afterSignOutUrl); }; const displayName = user.displayName || user.email?.split('@')[0] || 'User'; const avatarUrl = user.photoURL || undefined; const initials = displayName .split(' ') .map(n => n[0]) .join('') .toUpperCase() .slice(0, 2); // Extract custom menu items from children let customMenuItems: ReactElement[] = []; if (children) { React.Children.forEach(children, (child) => { if (React.isValidElement(child) && child.type === MenuItems) { React.Children.forEach(child.props.children, (menuItem) => { if (React.isValidElement(menuItem)) { customMenuItems.push(menuItem); } }); } }); } return ( {!avatarUrl && initials} {showName && ( <> {displayName} )} {!avatarUrl && initials}
{displayName} {user.email}
} onClick={() => router.push('/user-profile')} > Manage account {customMenuItems.length > 0 && ( <> {customMenuItems} )} } onClick={handleSignOut} color="red" > Sign out
); } // Attach sub-components UserButton.MenuItems = MenuItems; UserButton.Link = Link; UserButton.Action = Action;