v1.4: Segurança multi-tenant, file serving via API e UX humanizada
- Validação cross-tenant no login e rotas protegidas
- File serving via /api/files/{bucket}/{path} (eliminação DNS)
- Mensagens de erro humanizadas inline (sem pop-ups)
- Middleware tenant detection via headers customizados
- Upload de logos retorna URLs via API
- README atualizado com changelog v1.4 completo
This commit is contained in:
@@ -1,33 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface DynamicFaviconProps {
|
||||
logoUrl?: string;
|
||||
}
|
||||
|
||||
export default function DynamicFavicon({ logoUrl }: DynamicFaviconProps) {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!logoUrl) return;
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
// Remove favicons antigos
|
||||
const existingLinks = document.querySelectorAll("link[rel*='icon']");
|
||||
existingLinks.forEach(link => link.remove());
|
||||
useEffect(() => {
|
||||
if (!mounted || !logoUrl) return;
|
||||
|
||||
// Adiciona novo favicon
|
||||
const link = document.createElement('link');
|
||||
link.type = 'image/x-icon';
|
||||
link.rel = 'shortcut icon';
|
||||
link.href = logoUrl;
|
||||
document.getElementsByTagName('head')[0].appendChild(link);
|
||||
// Usar requestAnimationFrame para garantir que a hidratação terminou
|
||||
requestAnimationFrame(() => {
|
||||
// Remove favicons antigos
|
||||
const existingLinks = document.querySelectorAll("link[rel*='icon']");
|
||||
existingLinks.forEach(link => link.remove());
|
||||
|
||||
// Adiciona Apple touch icon
|
||||
const appleLink = document.createElement('link');
|
||||
appleLink.rel = 'apple-touch-icon';
|
||||
appleLink.href = logoUrl;
|
||||
document.getElementsByTagName('head')[0].appendChild(appleLink);
|
||||
// Adiciona novo favicon
|
||||
const link = document.createElement('link');
|
||||
link.type = 'image/x-icon';
|
||||
link.rel = 'shortcut icon';
|
||||
link.href = logoUrl;
|
||||
document.getElementsByTagName('head')[0].appendChild(link);
|
||||
|
||||
}, [logoUrl]);
|
||||
// Adiciona Apple touch icon
|
||||
const appleLink = document.createElement('link');
|
||||
appleLink.rel = 'apple-touch-icon';
|
||||
appleLink.href = logoUrl;
|
||||
document.getElementsByTagName('head')[0].appendChild(appleLink);
|
||||
});
|
||||
|
||||
}, [mounted, logoUrl]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,16 @@ import { isAuthenticated } from '@/lib/auth';
|
||||
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [authorized, setAuthorized] = useState(false);
|
||||
const [authorized, setAuthorized] = useState<boolean | null>(null);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
const checkAuth = () => {
|
||||
const isAuth = isAuthenticated();
|
||||
|
||||
@@ -35,12 +42,24 @@ export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [router, pathname]);
|
||||
}, [router, pathname, mounted]);
|
||||
|
||||
// Enquanto verifica (ou não está montado), mostra um loading simples
|
||||
// Isso evita problemas de hidratação mantendo a estrutura DOM consistente
|
||||
if (!mounted || authorized === null) {
|
||||
return (
|
||||
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Enquanto verifica, não renderiza nada ou um loading
|
||||
// Para evitar "flash" de conteúdo não autorizado
|
||||
if (!authorized) {
|
||||
return null;
|
||||
return (
|
||||
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
|
||||
138
front-end-agency/components/auth/LoginBranding.tsx
Normal file
138
front-end-agency/components/auth/LoginBranding.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* LoginBranding - Aplica cor primária da agência na página de login
|
||||
* Busca cor do localStorage ou da API se não houver cache
|
||||
*/
|
||||
export function LoginBranding() {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
const hexToRgb = (hex: string) => {
|
||||
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
|
||||
return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
|
||||
};
|
||||
|
||||
const applyTheme = (primary: string) => {
|
||||
if (!primary) return;
|
||||
|
||||
const root = document.documentElement;
|
||||
const primaryRgb = hexToRgb(primary);
|
||||
|
||||
root.style.setProperty('--brand-color', primary);
|
||||
root.style.setProperty('--gradient', `linear-gradient(135deg, ${primary}, ${primary})`);
|
||||
|
||||
if (primaryRgb) {
|
||||
root.style.setProperty('--brand-rgb', primaryRgb);
|
||||
root.style.setProperty('--brand-strong-rgb', primaryRgb);
|
||||
root.style.setProperty('--brand-hover-rgb', primaryRgb);
|
||||
}
|
||||
};
|
||||
|
||||
const updateFavicon = (url: string) => {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') return;
|
||||
|
||||
try {
|
||||
console.log('🎨 LoginBranding: Atualizando favicon para:', url);
|
||||
const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`;
|
||||
|
||||
// Buscar TODOS os links de ícone existentes
|
||||
const existingLinks = document.querySelectorAll("link[rel*='icon']");
|
||||
|
||||
if (existingLinks.length > 0) {
|
||||
// Atualizar href de todos os links existentes (SEM REMOVER)
|
||||
existingLinks.forEach(link => {
|
||||
link.setAttribute('href', newHref);
|
||||
});
|
||||
console.log(`✅ ${existingLinks.length} favicons atualizados`);
|
||||
} else {
|
||||
// Criar novo link apenas se não existir nenhum
|
||||
const newLink = document.createElement('link');
|
||||
newLink.rel = 'icon';
|
||||
newLink.type = 'image/x-icon';
|
||||
newLink.href = newHref;
|
||||
document.head.appendChild(newLink);
|
||||
console.log('✅ Novo favicon criado');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Erro ao atualizar favicon:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const loadBranding = async () => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const hostname = window.location.hostname;
|
||||
const subdomain = hostname.split('.')[0];
|
||||
|
||||
// Para dash.localhost ou localhost sem subdomínio, não buscar
|
||||
if (!subdomain || subdomain === 'localhost' || subdomain === 'www' || subdomain === 'dash') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Buscar DIRETO do backend (bypass da rota Next.js que está com problema)
|
||||
console.log('LoginBranding: Buscando cores para:', subdomain);
|
||||
const apiUrl = `/api/tenant/config?subdomain=${subdomain}`;
|
||||
console.log('LoginBranding: URL:', apiUrl);
|
||||
|
||||
const response = await fetch(apiUrl);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
console.log('LoginBranding: Dados recebidos:', data);
|
||||
|
||||
if (data.primary_color) {
|
||||
applyTheme(data.primary_color);
|
||||
localStorage.setItem('agency-primary-color', data.primary_color);
|
||||
console.log('LoginBranding: Cor aplicada!');
|
||||
}
|
||||
|
||||
if (data.logo_url) {
|
||||
updateFavicon(data.logo_url);
|
||||
localStorage.setItem('agency-logo-url', data.logo_url);
|
||||
console.log('LoginBranding: Favicon aplicado!');
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
console.error('LoginBranding: API retornou:', response.status);
|
||||
}
|
||||
|
||||
// 2. Fallback para cache
|
||||
console.log('LoginBranding: Tentando cache');
|
||||
const cachedPrimary = localStorage.getItem('agency-primary-color');
|
||||
const cachedLogo = localStorage.getItem('agency-logo-url');
|
||||
|
||||
if (cachedPrimary) {
|
||||
applyTheme(cachedPrimary);
|
||||
}
|
||||
if (cachedLogo) {
|
||||
updateFavicon(cachedLogo);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('LoginBranding: Erro:', error);
|
||||
const cachedPrimary = localStorage.getItem('agency-primary-color');
|
||||
const cachedLogo = localStorage.getItem('agency-logo-url');
|
||||
|
||||
if (cachedPrimary) {
|
||||
applyTheme(cachedPrimary);
|
||||
}
|
||||
if (cachedLogo) {
|
||||
updateFavicon(cachedLogo);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadBranding();
|
||||
}, [mounted]);
|
||||
|
||||
return null;
|
||||
}
|
||||
169
front-end-agency/components/layout/AgencyBranding.tsx
Normal file
169
front-end-agency/components/layout/AgencyBranding.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface AgencyBrandingProps {
|
||||
colors?: {
|
||||
primary: string;
|
||||
secondary: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* AgencyBranding - Aplica as cores da agência via CSS Variables
|
||||
* O favicon agora é tratado via Metadata API no layout (server-side)
|
||||
*/
|
||||
export function AgencyBranding({ colors }: AgencyBrandingProps) {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
const [debugInfo, setDebugInfo] = useState<string>('Iniciando...');
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
const hexToRgb = (hex: string) => {
|
||||
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
|
||||
return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : null;
|
||||
};
|
||||
|
||||
const applyTheme = (primary: string, secondary: string) => {
|
||||
if (!primary || !secondary) return;
|
||||
|
||||
const root = document.documentElement;
|
||||
const primaryRgb = hexToRgb(primary);
|
||||
const secondaryRgb = hexToRgb(secondary);
|
||||
|
||||
const gradient = `linear-gradient(135deg, ${primary}, ${primary})`;
|
||||
const gradientText = `linear-gradient(to right, ${primary}, ${primary})`;
|
||||
|
||||
root.style.setProperty('--gradient', gradient);
|
||||
root.style.setProperty('--gradient-text', gradientText);
|
||||
root.style.setProperty('--gradient-primary', gradient);
|
||||
root.style.setProperty('--color-gradient-brand', gradient);
|
||||
|
||||
root.style.setProperty('--brand-color', primary);
|
||||
root.style.setProperty('--brand-color-strong', secondary);
|
||||
|
||||
if (primaryRgb) root.style.setProperty('--brand-rgb', primaryRgb);
|
||||
if (secondaryRgb) root.style.setProperty('--brand-strong-rgb', secondaryRgb);
|
||||
|
||||
// Salvar no localStorage para cache
|
||||
if (typeof window !== 'undefined') {
|
||||
const hostname = window.location.hostname;
|
||||
const sub = hostname.split('.')[0];
|
||||
if (sub && sub !== 'www') {
|
||||
localStorage.setItem(`agency-theme:${sub}`, gradient);
|
||||
localStorage.setItem('agency-primary-color', primary);
|
||||
localStorage.setItem('agency-secondary-color', secondary);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const updateFavicon = (url: string) => {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') return;
|
||||
|
||||
try {
|
||||
setDebugInfo(`Tentando atualizar favicon: ${url}`);
|
||||
console.log('🎨 AgencyBranding: Atualizando favicon para:', url);
|
||||
|
||||
const newHref = `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`;
|
||||
|
||||
// Buscar TODOS os links de ícone existentes
|
||||
const existingLinks = document.querySelectorAll("link[rel*='icon']");
|
||||
|
||||
if (existingLinks.length > 0) {
|
||||
// Atualizar href de todos os links existentes (SEM REMOVER)
|
||||
existingLinks.forEach(link => {
|
||||
link.setAttribute('href', newHref);
|
||||
});
|
||||
setDebugInfo(`Favicon atualizado (${existingLinks.length} links)`);
|
||||
console.log(`✅ ${existingLinks.length} favicons atualizados`);
|
||||
} else {
|
||||
// Criar novo link apenas se não existir nenhum
|
||||
const newLink = document.createElement('link');
|
||||
newLink.rel = 'icon';
|
||||
newLink.type = 'image/x-icon';
|
||||
newLink.href = newHref;
|
||||
document.head.appendChild(newLink);
|
||||
setDebugInfo('Novo favicon criado');
|
||||
console.log('✅ Novo favicon criado');
|
||||
}
|
||||
} catch (error) {
|
||||
setDebugInfo(`Erro: ${error}`);
|
||||
console.error('❌ Erro ao atualizar favicon:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Se temos cores do servidor, aplicar imediatamente
|
||||
if (colors) {
|
||||
applyTheme(colors.primary, colors.secondary);
|
||||
} else {
|
||||
// Fallback: tentar pegar do cache do localStorage
|
||||
const cachedPrimary = localStorage.getItem('agency-primary-color');
|
||||
const cachedSecondary = localStorage.getItem('agency-secondary-color');
|
||||
|
||||
if (cachedPrimary && cachedSecondary) {
|
||||
applyTheme(cachedPrimary, cachedSecondary);
|
||||
}
|
||||
}
|
||||
|
||||
// Atualizar favicon se houver logo salvo (após montar)
|
||||
const cachedLogo = localStorage.getItem('agency-logo-url');
|
||||
if (cachedLogo) {
|
||||
console.log('🔍 Logo encontrado no cache:', cachedLogo);
|
||||
updateFavicon(cachedLogo);
|
||||
} else {
|
||||
setDebugInfo('Nenhum logo no cache');
|
||||
console.log('⚠️ Nenhum logo encontrado no cache');
|
||||
}
|
||||
|
||||
// Listener para atualizações em tempo real (ex: da página de configurações)
|
||||
const handleUpdate = () => {
|
||||
console.log('🔔 Evento branding-update recebido!');
|
||||
setDebugInfo('Evento branding-update recebido');
|
||||
|
||||
const cachedPrimary = localStorage.getItem('agency-primary-color');
|
||||
const cachedSecondary = localStorage.getItem('agency-secondary-color');
|
||||
const cachedLogo = localStorage.getItem('agency-logo-url');
|
||||
|
||||
if (cachedPrimary && cachedSecondary) {
|
||||
console.log('🎨 Aplicando cores do cache');
|
||||
applyTheme(cachedPrimary, cachedSecondary);
|
||||
}
|
||||
|
||||
if (cachedLogo) {
|
||||
console.log('🖼️ Atualizando favicon do cache:', cachedLogo);
|
||||
updateFavicon(cachedLogo);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('branding-update', handleUpdate);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('branding-update', handleUpdate);
|
||||
};
|
||||
}, [mounted, colors]);
|
||||
|
||||
if (!mounted) return null;
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed',
|
||||
bottom: '10px',
|
||||
left: '10px',
|
||||
background: 'rgba(0,0,0,0.8)',
|
||||
color: 'white',
|
||||
padding: '5px 10px',
|
||||
borderRadius: '4px',
|
||||
fontSize: '10px',
|
||||
zIndex: 9999,
|
||||
pointerEvents: 'none'
|
||||
}}>
|
||||
DEBUG: {debugInfo}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { SidebarRail, MenuItem } from './SidebarRail';
|
||||
import { TopBar } from './TopBar';
|
||||
|
||||
@@ -12,14 +13,12 @@ interface DashboardLayoutProps {
|
||||
export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children, menuItems }) => {
|
||||
// Estado centralizado do layout
|
||||
const [isExpanded, setIsExpanded] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState('dashboard');
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-full bg-gray-100 dark:bg-zinc-950 text-slate-900 dark:text-slate-100 overflow-hidden p-3 gap-3 transition-colors duration-300">
|
||||
{/* Sidebar controla seu próprio estado visual via props */}
|
||||
<SidebarRail
|
||||
activeTab={activeTab}
|
||||
onTabChange={setActiveTab}
|
||||
isExpanded={isExpanded}
|
||||
onToggle={() => setIsExpanded(!isExpanded)}
|
||||
menuItems={menuItems}
|
||||
@@ -32,7 +31,9 @@ export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children, menu
|
||||
|
||||
{/* Conteúdo das páginas */}
|
||||
<div className="flex-1 overflow-auto">
|
||||
{children}
|
||||
<div className="max-w-7xl mx-auto w-full h-full">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
54
front-end-agency/components/layout/FaviconUpdater.tsx
Normal file
54
front-end-agency/components/layout/FaviconUpdater.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export function FaviconUpdater() {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
const updateFavicon = () => {
|
||||
const user = getUser();
|
||||
if (user?.logoUrl) {
|
||||
// Usar requestAnimationFrame para garantir que o DOM esteja estável após hidratação
|
||||
requestAnimationFrame(() => {
|
||||
const link: HTMLLinkElement = document.querySelector("link[rel*='icon']") || document.createElement('link');
|
||||
link.type = 'image/x-icon';
|
||||
link.rel = 'shortcut icon';
|
||||
link.href = user.logoUrl!;
|
||||
if (!link.parentNode) {
|
||||
document.getElementsByTagName('head')[0].appendChild(link);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Atraso pequeno para garantir que a hidratação terminou
|
||||
const timer = setTimeout(() => {
|
||||
updateFavicon();
|
||||
}, 0);
|
||||
|
||||
// Ouve mudanças no localStorage
|
||||
const handleStorage = () => {
|
||||
requestAnimationFrame(() => updateFavicon());
|
||||
};
|
||||
window.addEventListener('storage', handleStorage);
|
||||
|
||||
// Custom event para atualização interna na mesma aba
|
||||
window.addEventListener('auth-update', handleStorage);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
window.removeEventListener('auth-update', handleStorage);
|
||||
};
|
||||
}, [mounted]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { Menu, Transition } from '@headlessui/react';
|
||||
import { Fragment } from 'react';
|
||||
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/react';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { getUser, User, getToken, saveAuth } from '@/lib/auth';
|
||||
import { API_ENDPOINTS } from '@/lib/api';
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
@@ -30,16 +31,12 @@ export interface MenuItem {
|
||||
}
|
||||
|
||||
interface SidebarRailProps {
|
||||
activeTab: string;
|
||||
onTabChange: (tab: string) => void;
|
||||
isExpanded: boolean;
|
||||
onToggle: () => void;
|
||||
menuItems: MenuItem[];
|
||||
}
|
||||
|
||||
export const SidebarRail: React.FC<SidebarRailProps> = ({
|
||||
activeTab,
|
||||
onTabChange,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
menuItems,
|
||||
@@ -48,12 +45,93 @@ export const SidebarRail: React.FC<SidebarRailProps> = ({
|
||||
const router = useRouter();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [openSubmenu, setOpenSubmenu] = useState<string | null>(null);
|
||||
const sidebarRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
const currentUser = getUser();
|
||||
setUser(currentUser);
|
||||
|
||||
// Buscar perfil da agência para atualizar logo e nome
|
||||
const fetchProfile = async () => {
|
||||
const token = getToken();
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(API_ENDPOINTS.agencyProfile, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (currentUser) {
|
||||
const updatedUser = {
|
||||
...currentUser,
|
||||
company: data.name || currentUser.company,
|
||||
logoUrl: data.logo_url
|
||||
};
|
||||
setUser(updatedUser);
|
||||
saveAuth(token, updatedUser); // Persistir atualização
|
||||
|
||||
// Atualizar localStorage do logo para uso do favicon
|
||||
if (data.logo_url) {
|
||||
console.log('📝 Salvando logo no localStorage:', data.logo_url);
|
||||
localStorage.setItem('agency-logo-url', data.logo_url);
|
||||
window.dispatchEvent(new Event('auth-update')); // Notificar favicon
|
||||
window.dispatchEvent(new Event('branding-update')); // Notificar AgencyBranding
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching agency profile:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchProfile();
|
||||
|
||||
// Listener para atualizar logo em tempo real após upload
|
||||
// REMOVIDO: Causa loop infinito com o dispatchEvent dentro do fetchProfile
|
||||
// O AgencyBranding já cuida de atualizar o favicon/cores
|
||||
// Se precisar atualizar o sidebar após upload, usar um evento específico 'logo-uploaded'
|
||||
/*
|
||||
const handleBrandingUpdate = () => {
|
||||
console.log('SidebarRail: branding-update event received');
|
||||
fetchProfile(); // Re-buscar perfil do backend
|
||||
};
|
||||
|
||||
window.addEventListener('branding-update', handleBrandingUpdate);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('branding-update', handleBrandingUpdate);
|
||||
};
|
||||
*/
|
||||
}, []);
|
||||
|
||||
// Fechar submenu ao clicar fora
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (sidebarRef.current && !sidebarRef.current.contains(event.target as Node)) {
|
||||
// Verifica se o submenu aberto corresponde à rota atual
|
||||
// Se estivermos navegando dentro do módulo (ex: CRM), o menu deve permanecer fixo
|
||||
const activeItem = menuItems.find(item => item.id === openSubmenu);
|
||||
const isRouteActive = activeItem && activeItem.subItems?.some(sub => pathname === sub.href || pathname.startsWith(sub.href));
|
||||
|
||||
if (!isRouteActive) {
|
||||
setOpenSubmenu(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [openSubmenu, pathname, menuItems]);
|
||||
|
||||
// Auto-open submenu if active
|
||||
useEffect(() => {
|
||||
if (isExpanded && pathname) {
|
||||
@@ -69,7 +147,7 @@ export const SidebarRail: React.FC<SidebarRailProps> = ({
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
router.push('/login');
|
||||
window.location.href = '/login';
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
@@ -79,46 +157,59 @@ export const SidebarRail: React.FC<SidebarRailProps> = ({
|
||||
// Encontrar o item ativo para renderizar o submenu
|
||||
const activeMenuItem = menuItems.find(item => item.id === openSubmenu);
|
||||
|
||||
// Lógica de largura do Rail: Se tiver submenu aberto, força recolhimento visual (80px)
|
||||
// Se não, respeita o estado isExpanded
|
||||
const railWidth = isExpanded && !openSubmenu ? 'w-[240px]' : 'w-[80px]';
|
||||
const showLabels = isExpanded && !openSubmenu;
|
||||
|
||||
return (
|
||||
<div className="flex h-full relative z-20">
|
||||
<div className={`flex h-full relative z-20 transition-all duration-300 ${openSubmenu ? 'shadow-xl' : 'shadow-lg'} rounded-2xl`} ref={sidebarRef}>
|
||||
{/* Rail Principal (Ícones + Labels Opcionais) */}
|
||||
<div
|
||||
className={`
|
||||
relative h-full bg-white dark:bg-zinc-900 rounded-2xl flex flex-col py-4 gap-1 text-gray-600 dark:text-gray-400 shrink-0 shadow-lg z-20
|
||||
transition-all duration-300 ease-[cubic-bezier(0.25,0.1,0.25,1)] px-3 border border-transparent dark:border-zinc-800
|
||||
${isExpanded ? 'w-[240px]' : 'w-[80px]'}
|
||||
`}
|
||||
relative h-full bg-white dark:bg-zinc-900 flex flex-col py-4 gap-1 text-gray-600 dark:text-gray-400 shrink-0 z-30
|
||||
transition-all duration-300 ease-[cubic-bezier(0.25,0.1,0.25,1)] px-3 border border-gray-100 dark:border-zinc-800
|
||||
${railWidth}
|
||||
${openSubmenu ? 'rounded-l-2xl rounded-r-none border-r-0' : 'rounded-2xl'}
|
||||
`}
|
||||
>
|
||||
{/* Toggle Button - Floating on the border */}
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className="absolute -right-3 top-8 z-50 flex h-6 w-6 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-500 shadow-sm hover:bg-gray-50 hover:text-gray-700 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200 transition-colors"
|
||||
aria-label={isExpanded ? 'Recolher menu' : 'Expandir menu'}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronLeftIcon className="w-3 h-3" />
|
||||
) : (
|
||||
<ChevronRightIcon className="w-3 h-3" />
|
||||
)}
|
||||
</button>
|
||||
{/* Só mostra o toggle se não tiver submenu aberto, para evitar confusão */}
|
||||
{!openSubmenu && (
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className="absolute -right-3 top-8 z-50 flex h-6 w-6 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-500 shadow-sm hover:bg-gray-50 hover:text-gray-700 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200 transition-colors"
|
||||
aria-label={isExpanded ? 'Recolher menu' : 'Expandir menu'}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronLeftIcon className="w-3 h-3" />
|
||||
) : (
|
||||
<ChevronRightIcon className="w-3 h-3" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Header com Logo */}
|
||||
<div className={`flex items-center w-full mb-6 ${isExpanded ? 'justify-start px-1' : 'justify-center'}`}>
|
||||
{/* Logo */}
|
||||
<div className={`flex items-center w-full mb-6 ${showLabels ? 'justify-start px-1' : 'justify-center'}`}>
|
||||
<div
|
||||
className="w-9 h-9 rounded-xl flex items-center justify-center text-white font-bold shrink-0 shadow-md text-lg"
|
||||
style={{ background: 'var(--gradient)' }}
|
||||
className="w-9 h-9 rounded-xl flex items-center justify-center text-white font-bold shrink-0 shadow-md text-lg overflow-hidden bg-brand-500"
|
||||
>
|
||||
A
|
||||
{user?.logoUrl ? (
|
||||
<img src={user.logoUrl} alt={user.company || 'Logo'} className="w-full h-full object-cover" />
|
||||
) : (
|
||||
(user?.company?.[0] || 'A').toUpperCase()
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Título com animação */}
|
||||
<div className={`overflow-hidden transition-all duration-300 ease-in-out whitespace-nowrap ${isExpanded ? 'opacity-100 max-w-[120px] ml-3' : 'opacity-0 max-w-0 ml-0'}`}>
|
||||
<span className="font-heading font-bold text-lg text-gray-900 dark:text-white tracking-tight">Aggios</span>
|
||||
<div className={`overflow-hidden transition-all duration-300 ease-in-out whitespace-nowrap ${showLabels ? 'opacity-100 max-w-[120px] ml-3' : 'opacity-0 max-w-0 ml-0'}`}>
|
||||
<span className="font-heading font-bold text-lg text-gray-900 dark:text-white tracking-tight">
|
||||
{user?.company || 'Aggios'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navegação */}
|
||||
<div className="flex flex-col gap-1 w-full flex-1 overflow-y-auto">
|
||||
<div className="flex flex-col gap-1 w-full flex-1 overflow-y-auto items-center">
|
||||
{menuItems.map((item) => (
|
||||
<RailButton
|
||||
key={item.id}
|
||||
@@ -126,117 +217,117 @@ export const SidebarRail: React.FC<SidebarRailProps> = ({
|
||||
icon={item.icon}
|
||||
href={item.href}
|
||||
active={pathname === item.href || (item.href !== '/dashboard' && pathname?.startsWith(item.href))}
|
||||
onClick={() => {
|
||||
onClick={(e: any) => {
|
||||
if (item.subItems) {
|
||||
setOpenSubmenu(openSubmenu === item.id ? null : item.id);
|
||||
// Se já estiver aberto, fecha e previne navegação (opcional)
|
||||
if (openSubmenu === item.id) {
|
||||
// Se quisermos permitir fechar sem navegar:
|
||||
// e.preventDefault();
|
||||
// setOpenSubmenu(null);
|
||||
|
||||
// Mas se o usuário quer ir para a home do módulo, deixamos navegar.
|
||||
// O useEffect vai reabrir se a rota for do módulo.
|
||||
// Para forçar o fechamento, teríamos que ter lógica mais complexa.
|
||||
// Vamos assumir que clicar no pai sempre leva pra home do pai.
|
||||
// E o useEffect cuida de abrir o menu.
|
||||
// Então NÃO fazemos nada aqui se for abrir.
|
||||
} else {
|
||||
// Se for abrir, deixamos o Link navegar.
|
||||
// O useEffect vai abrir o menu quando a rota mudar.
|
||||
// NÃO setamos o estado aqui para evitar conflito com a navegação.
|
||||
}
|
||||
} else {
|
||||
onTabChange(item.id);
|
||||
setOpenSubmenu(null);
|
||||
}
|
||||
}}
|
||||
isExpanded={isExpanded}
|
||||
showLabel={showLabels}
|
||||
hasSubItems={!!item.subItems}
|
||||
isOpen={openSubmenu === item.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Separador antes do menu de usuário */}
|
||||
<div className="h-px bg-gray-200 dark:bg-zinc-800 my-2" />
|
||||
{/* Separador */}
|
||||
<div className="h-px bg-gray-200 dark:bg-zinc-800 my-2 w-full" />
|
||||
|
||||
{/* User Menu - Footer */}
|
||||
<div>
|
||||
<Menu as="div" className="relative">
|
||||
<Menu.Button className={`w-full p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-zinc-800 transition-all duration-300 flex items-center ${isExpanded ? '' : 'justify-center'}`}>
|
||||
<UserCircleIcon className="w-5 h-5 shrink-0 text-gray-600 dark:text-gray-400" />
|
||||
<div className={`overflow-hidden whitespace-nowrap transition-all duration-300 ease-in-out ${isExpanded ? 'max-w-[150px] opacity-100 ml-2' : 'max-w-0 opacity-0 ml-0'}`}>
|
||||
<span className="font-medium text-xs text-gray-900 dark:text-white">Agência</span>
|
||||
</div>
|
||||
</Menu.Button>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items className={`absolute ${isExpanded ? 'left-0' : 'left-14'} bottom-0 mb-2 w-48 origin-bottom-left rounded-xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-lg focus:outline-none overflow-hidden z-50`}>
|
||||
<div className="p-1">
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
className={`${active ? 'bg-gray-100 dark:bg-zinc-800' : ''} text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs`}
|
||||
>
|
||||
<UserCircleIcon className="mr-2 h-4 w-4" />
|
||||
Ver meu perfil
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<Link
|
||||
href="/configuracoes"
|
||||
className={`${active ? 'bg-gray-100 dark:bg-zinc-800' : ''} text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs`}
|
||||
>
|
||||
<Cog6ToothIcon className="mr-2 h-4 w-4" />
|
||||
Configurações
|
||||
</Link>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
className={`${active ? 'bg-gray-100 dark:bg-zinc-800' : ''} text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs`}
|
||||
>
|
||||
{mounted && theme === 'dark' ? (
|
||||
<>
|
||||
<SunIcon className="mr-2 h-4 w-4" />
|
||||
Tema Claro
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<MoonIcon className="mr-2 h-4 w-4" />
|
||||
Tema Escuro
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<div className="my-1 h-px bg-gray-200 dark:bg-zinc-800" />
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''} text-red-500 group flex w-full items-center rounded-lg px-3 py-2 text-xs`}
|
||||
>
|
||||
<ArrowRightOnRectangleIcon className="mr-2 h-4 w-4" />
|
||||
Sair
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
{/* User Menu */}
|
||||
<div className={`flex ${showLabels ? 'justify-start' : 'justify-center'}`}>
|
||||
{mounted && (
|
||||
<Menu>
|
||||
<MenuButton className={`w-full p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-zinc-800 transition-all duration-300 flex items-center ${showLabels ? '' : 'justify-center'}`}>
|
||||
<UserCircleIcon className="w-6 h-6 text-gray-600 dark:text-gray-400 shrink-0" />
|
||||
<div className={`overflow-hidden whitespace-nowrap transition-all duration-300 ease-in-out ${showLabels ? 'max-w-[150px] opacity-100 ml-2' : 'max-w-0 opacity-0 ml-0'}`}>
|
||||
<span className="font-medium text-xs text-gray-900 dark:text-white">
|
||||
{user?.name || 'Usuário'}
|
||||
</span>
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
</MenuButton>
|
||||
<MenuItems
|
||||
anchor="top start"
|
||||
transition
|
||||
className={`w-48 origin-bottom-left rounded-xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-lg focus:outline-none overflow-hidden z-50 transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0`}
|
||||
>
|
||||
<div className="p-1">
|
||||
<MenuItem>
|
||||
<button
|
||||
className="data-[focus]:bg-gray-100 dark:data-[focus]:bg-zinc-800 text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs"
|
||||
>
|
||||
<UserCircleIcon className="mr-2 h-4 w-4" />
|
||||
Ver meu perfil
|
||||
</button>
|
||||
</MenuItem>
|
||||
<MenuItem>
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
className="data-[focus]:bg-gray-100 dark:data-[focus]:bg-zinc-800 text-gray-700 dark:text-gray-300 group flex w-full items-center rounded-lg px-3 py-2 text-xs"
|
||||
>
|
||||
{theme === 'dark' ? (
|
||||
<>
|
||||
<SunIcon className="mr-2 h-4 w-4" />
|
||||
Tema Claro
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<MoonIcon className="mr-2 h-4 w-4" />
|
||||
Tema Escuro
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</MenuItem>
|
||||
<div className="my-1 h-px bg-gray-200 dark:bg-zinc-800" />
|
||||
<MenuItem>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="data-[focus]:bg-red-50 dark:data-[focus]:bg-red-900/20 text-red-500 group flex w-full items-center rounded-lg px-3 py-2 text-xs"
|
||||
>
|
||||
<ArrowRightOnRectangleIcon className="mr-2 h-4 w-4" />
|
||||
Sair
|
||||
</button>
|
||||
</MenuItem>
|
||||
</div>
|
||||
</MenuItems>
|
||||
</Menu>
|
||||
)}
|
||||
{!mounted && (
|
||||
<div className={`w-full p-2 rounded-lg flex items-center ${showLabels ? '' : 'justify-center'}`}>
|
||||
<UserCircleIcon className="w-6 h-6 text-gray-600 dark:text-gray-400 shrink-0" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submenu Flyout Panel */}
|
||||
{/* Painel Secundário (Drawer) - Abre ao lado do Rail */}
|
||||
<div
|
||||
className={`
|
||||
absolute top-0 bottom-0 left-[calc(100%+12px)] w-64
|
||||
bg-white dark:bg-zinc-900 rounded-2xl shadow-xl border border-gray-100 dark:border-zinc-800
|
||||
transition-all duration-300 ease-in-out origin-left z-10 flex flex-col overflow-hidden
|
||||
${openSubmenu ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-4 pointer-events-none'}
|
||||
h-full
|
||||
bg-white dark:bg-zinc-900 rounded-r-2xl border-y border-r border-l border-gray-100 dark:border-zinc-800
|
||||
transition-all duration-300 ease-in-out origin-left z-20 flex flex-col overflow-hidden
|
||||
${openSubmenu ? 'w-64 opacity-100 translate-x-0' : 'w-0 opacity-0 -translate-x-10 border-none'}
|
||||
`}
|
||||
>
|
||||
{activeMenuItem && (
|
||||
<>
|
||||
<div className="p-4 border-b border-gray-100 dark:border-zinc-800 bg-gray-50/50 dark:bg-zinc-800/50 flex items-center justify-between">
|
||||
<div className="p-4 border-b border-gray-100 dark:border-zinc-800 flex items-center justify-between">
|
||||
<h3 className="font-heading font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<activeMenuItem.icon className="w-5 h-5 text-brand-500" />
|
||||
{activeMenuItem.label}
|
||||
@@ -254,7 +345,7 @@ export const SidebarRail: React.FC<SidebarRailProps> = ({
|
||||
<Link
|
||||
key={sub.href}
|
||||
href={sub.href}
|
||||
onClick={() => setOpenSubmenu(null)} // Fecha ao clicar
|
||||
// onClick={() => setOpenSubmenu(null)} // Removido para manter fixo
|
||||
className={`
|
||||
flex items-center gap-2 px-3 py-2.5 rounded-lg text-xs font-medium transition-colors mb-1
|
||||
${pathname === sub.href
|
||||
@@ -281,25 +372,31 @@ interface RailButtonProps {
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
href: string;
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
isExpanded: boolean;
|
||||
onClick: (e?: any) => void;
|
||||
showLabel: boolean;
|
||||
hasSubItems?: boolean;
|
||||
isOpen?: boolean;
|
||||
}
|
||||
|
||||
const RailButton: React.FC<RailButtonProps> = ({ label, icon: Icon, href, active, onClick, isExpanded, hasSubItems, isOpen }) => {
|
||||
const Wrapper = hasSubItems ? 'button' : Link;
|
||||
const props = hasSubItems ? { onClick, type: 'button' } : { href, onClick };
|
||||
|
||||
const RailButton: React.FC<RailButtonProps> = ({ label, icon: Icon, href, active, onClick, showLabel, hasSubItems, isOpen }) => {
|
||||
// Determine styling based on state
|
||||
let baseClasses = "flex items-center p-2 rounded-lg transition-all duration-300 group relative overflow-hidden w-full ";
|
||||
// Sempre usa Link se tiver href, para garantir navegação correta e prefetching
|
||||
const Wrapper = href ? Link : 'button';
|
||||
// Desabilitar prefetch para evitar sobrecarga no middleware/backend e loops de redirecionamento
|
||||
const props = href ? { href, onClick, prefetch: false } : { onClick, type: 'button' };
|
||||
|
||||
if (active && !hasSubItems) {
|
||||
// Active leaf item (Dashboard, etc)
|
||||
baseClasses += "text-white shadow-md";
|
||||
} else if (isOpen) {
|
||||
// Open submenu parent - Highlight to show active state
|
||||
baseClasses += "bg-gray-100 dark:bg-zinc-800 text-gray-900 dark:text-white";
|
||||
let baseClasses = "flex items-center p-2 rounded-lg transition-all duration-300 group relative overflow-hidden ";
|
||||
if (showLabel) {
|
||||
baseClasses += "w-full justify-start ";
|
||||
} else {
|
||||
baseClasses += "w-10 h-10 justify-center mx-auto ";
|
||||
}
|
||||
|
||||
// Lógica unificada de ativo
|
||||
const isActiveItem = active || isOpen;
|
||||
|
||||
if (isActiveItem) {
|
||||
baseClasses += "bg-brand-500 text-white shadow-sm";
|
||||
} else {
|
||||
// Inactive item
|
||||
baseClasses += "hover:bg-gray-100 dark:hover:bg-zinc-800 hover:text-gray-900 dark:hover:text-white text-gray-600 dark:text-gray-400";
|
||||
@@ -308,29 +405,26 @@ const RailButton: React.FC<RailButtonProps> = ({ label, icon: Icon, href, active
|
||||
return (
|
||||
<Wrapper
|
||||
{...props as any}
|
||||
style={{ background: active && !hasSubItems ? 'var(--gradient)' : undefined }}
|
||||
className={`${baseClasses} ${isExpanded ? '' : 'justify-center'}`}
|
||||
className={baseClasses}
|
||||
title={!showLabel ? label : undefined} // Tooltip nativo apenas se recolhido
|
||||
>
|
||||
{/* Ícone */}
|
||||
<Icon className={`shrink-0 w-4 h-4 ${isOpen ? 'text-brand-500' : ''}`} />
|
||||
<Icon className={`shrink-0 w-5 h-5 ${isActiveItem ? 'text-white' : ''}`} />
|
||||
|
||||
{/* Lógica Mágica do Texto: Max-Width Transition */}
|
||||
{/* Texto (Visível apenas se expandido) */}
|
||||
<div className={`
|
||||
overflow-hidden whitespace-nowrap transition-all duration-300 ease-in-out flex items-center flex-1
|
||||
${isExpanded ? 'max-w-[150px] opacity-100 ml-2' : 'max-w-0 opacity-0 ml-0'}
|
||||
`}>
|
||||
overflow-hidden whitespace-nowrap transition-all duration-300 ease-in-out flex items-center flex-1
|
||||
${showLabel ? 'max-w-[150px] opacity-100 ml-3' : 'max-w-0 opacity-0 ml-0'}
|
||||
`}>
|
||||
<span className="font-medium text-xs flex-1 text-left">{label}</span>
|
||||
{hasSubItems && (
|
||||
<ChevronRightIcon className={`w-3 h-3 transition-transform duration-200 ${isOpen ? 'text-brand-500' : 'text-gray-400'}`} />
|
||||
<ChevronRightIcon className={`w-3 h-3 transition-transform duration-200 ${isActiveItem ? 'text-white' : 'text-gray-400'}`} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Indicador de Ativo (Barra lateral pequena quando fechado) */}
|
||||
{active && !isExpanded && !hasSubItems && (
|
||||
<div
|
||||
className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-3 rounded-r-full -ml-3"
|
||||
style={{ background: 'var(--gradient)' }}
|
||||
/>
|
||||
{/* Indicador de Ativo (Ponto lateral) - Apenas se recolhido e NÃO tiver gradiente (redundante agora, mas mantido por segurança) */}
|
||||
{active && !hasSubItems && !showLabel && !isActiveItem && (
|
||||
<div className="absolute -left-1 top-1/2 -translate-y-1/2 w-1 h-4 bg-white rounded-r-full" />
|
||||
)}
|
||||
</Wrapper>
|
||||
);
|
||||
|
||||
@@ -3,20 +3,18 @@
|
||||
import React, { useState } from 'react';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { MagnifyingGlassIcon, ChevronRightIcon, HomeIcon } from '@heroicons/react/24/outline';
|
||||
import { MagnifyingGlassIcon, ChevronRightIcon, HomeIcon, BellIcon, Cog6ToothIcon } from '@heroicons/react/24/outline';
|
||||
import CommandPalette from '@/components/ui/CommandPalette';
|
||||
|
||||
export const TopBar: React.FC = () => {
|
||||
const pathname = usePathname();
|
||||
const [isCommandPaletteOpen, setIsCommandPaletteOpen] = useState(false);
|
||||
|
||||
// Gerar breadcrumbs a partir do pathname
|
||||
const generateBreadcrumbs = () => {
|
||||
const paths = pathname?.split('/').filter(Boolean) || [];
|
||||
const breadcrumbs: Array<{ name: string; href: string; icon?: React.ComponentType<{ className?: string }> }> = [
|
||||
{ name: 'Home', href: '/dashboard', icon: HomeIcon }
|
||||
];
|
||||
|
||||
let currentPath = '';
|
||||
paths.forEach((path, index) => {
|
||||
currentPath += `/${path}`;
|
||||
@@ -82,19 +80,30 @@ export const TopBar: React.FC = () => {
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setIsCommandPaletteOpen(true)}
|
||||
className="group relative flex items-center gap-2 px-3 py-1.5 bg-gray-50 dark:bg-zinc-800 hover:bg-gray-100 dark:hover:bg-zinc-700 border border-gray-200 dark:border-zinc-700 rounded-lg text-xs text-gray-500 dark:text-zinc-400 hover:text-gray-900 dark:hover:text-zinc-200 transition-all w-64"
|
||||
className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-500 dark:text-zinc-400 bg-gray-100 dark:bg-zinc-800 rounded-lg hover:bg-gray-200 dark:hover:bg-zinc-700 transition-colors"
|
||||
>
|
||||
<MagnifyingGlassIcon className="w-4 h-4 text-gray-400 dark:text-zinc-500 group-hover:text-gray-600 dark:group-hover:text-zinc-300" />
|
||||
<span>Pesquisar...</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<kbd className="hidden sm:inline-block px-1.5 py-0.5 text-[10px] font-mono font-medium text-gray-500 dark:text-zinc-400 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-700 rounded shadow-sm">
|
||||
Ctrl K
|
||||
</kbd>
|
||||
</div>
|
||||
<MagnifyingGlassIcon className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Buscar...</span>
|
||||
<kbd className="hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium text-gray-400 bg-white dark:bg-zinc-900 rounded border border-gray-200 dark:border-zinc-700">
|
||||
Ctrl K
|
||||
</kbd>
|
||||
</button>
|
||||
<div className="flex items-center gap-2 border-l border-gray-200 dark:border-zinc-800 pl-4">
|
||||
<button className="p-2 text-gray-500 dark:text-zinc-400 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg transition-colors relative">
|
||||
<BellIcon className="w-5 h-5" />
|
||||
<span className="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full border-2 border-white dark:border-zinc-900"></span>
|
||||
</button>
|
||||
<Link
|
||||
href="/configuracoes"
|
||||
className="p-2 text-gray-500 dark:text-zinc-400 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
|
||||
>
|
||||
<Cog6ToothIcon className="w-5 h-5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Command Palette */}
|
||||
<CommandPalette isOpen={isCommandPaletteOpen} setIsOpen={setIsCommandPaletteOpen} />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -29,30 +29,48 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
"inline-flex items-center justify-center font-medium rounded-[6px] transition-opacity focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer";
|
||||
|
||||
const variants = {
|
||||
primary: "text-white hover:opacity-90 active:opacity-80",
|
||||
primary: "bg-brand-500 text-white hover:opacity-90 active:opacity-80 shadow-sm hover:shadow-md transition-all",
|
||||
secondary:
|
||||
"bg-[#E5E5E5] dark:bg-gray-700 text-[#000000] dark:text-white hover:opacity-90 active:opacity-80",
|
||||
"bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-700 active:bg-gray-300 dark:active:bg-gray-600",
|
||||
outline:
|
||||
"border border-[#E5E5E5] dark:border-gray-600 text-[#000000] dark:text-white hover:bg-[#E5E5E5]/10 dark:hover:bg-gray-700/50 active:bg-[#E5E5E5]/20 dark:active:bg-gray-700",
|
||||
ghost: "text-[#000000] dark:text-white hover:bg-[#E5E5E5]/20 dark:hover:bg-gray-700/30 active:bg-[#E5E5E5]/30 dark:active:bg-gray-700/50",
|
||||
"border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 active:bg-gray-100 dark:active:bg-gray-700",
|
||||
ghost: "text-gray-700 dark:text-white hover:bg-gray-100 dark:hover:bg-gray-800 active:bg-gray-200 dark:active:bg-gray-700",
|
||||
};
|
||||
|
||||
const sizes = {
|
||||
sm: "h-9 px-3 text-[13px]",
|
||||
md: "h-10 px-4 text-[14px]",
|
||||
lg: "h-12 px-6 text-[14px]",
|
||||
sm: "h-8 px-3 text-xs",
|
||||
md: "h-10 px-4 text-sm",
|
||||
lg: "h-12 px-6 text-base",
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
className={`${baseStyles} ${variants[variant]} ${sizes[size]} ${className}`}
|
||||
style={variant === 'primary' ? { background: 'var(--gradient-primary)' } : undefined}
|
||||
disabled={disabled || isLoading}
|
||||
{...props}
|
||||
>
|
||||
{isLoading && (
|
||||
<i className="ri-loader-4-line animate-spin mr-2 text-[20px]" />
|
||||
<svg
|
||||
className="animate-spin -ml-1 mr-2 h-4 w-4 text-current"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
></circle>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
></path>
|
||||
</svg>
|
||||
)}
|
||||
{!isLoading && leftIcon && (
|
||||
<i className={`${leftIcon} mr-2 text-[20px]`} />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Fragment, useState, useEffect, useRef } from 'react';
|
||||
import { Combobox, Dialog, Transition } from '@headlessui/react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Combobox, Dialog, DialogBackdrop, DialogPanel } from '@headlessui/react';
|
||||
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
@@ -84,123 +84,107 @@ export default function CommandPalette({ isOpen, setIsOpen }: CommandPaletteProp
|
||||
};
|
||||
|
||||
return (
|
||||
<Transition.Root show={isOpen} as={Fragment} afterLeave={() => setQuery('')}>
|
||||
<Dialog as="div" className="relative z-50" onClose={setIsOpen} initialFocus={inputRef}>
|
||||
<Transition.Child
|
||||
as={Fragment}
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0"
|
||||
enterTo="opacity-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
<Dialog open={isOpen} onClose={setIsOpen} className="relative z-50" initialFocus={inputRef}>
|
||||
<DialogBackdrop
|
||||
transition
|
||||
className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity duration-300 data-[closed]:opacity-0"
|
||||
/>
|
||||
|
||||
<div className="fixed inset-0 z-10 overflow-y-auto p-4 sm:p-6 md:p-20">
|
||||
<DialogPanel
|
||||
transition
|
||||
className="mx-auto max-w-2xl transform overflow-hidden rounded-xl bg-white dark:bg-zinc-900 shadow-2xl transition-all duration-300 data-[closed]:opacity-0 data-[closed]:scale-95"
|
||||
>
|
||||
<div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" />
|
||||
</Transition.Child>
|
||||
<Combobox onChange={handleSelect}>
|
||||
<div className="relative">
|
||||
<MagnifyingGlassIcon
|
||||
className="pointer-events-none absolute left-4 top-3.5 h-5 w-5 text-zinc-400"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Combobox.Input
|
||||
ref={inputRef}
|
||||
className="h-12 w-full border-0 bg-transparent pl-11 pr-4 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:ring-0 sm:text-sm font-medium"
|
||||
placeholder="O que você procura?"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
displayValue={(item: any) => item?.name}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="fixed inset-0 z-10 overflow-y-auto p-4 sm:p-6 md:p-20">
|
||||
<Transition.Child
|
||||
as={Fragment}
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Dialog.Panel className="mx-auto max-w-2xl transform overflow-hidden rounded-xl bg-white dark:bg-zinc-900 shadow-2xl transition-all">
|
||||
<Combobox onChange={handleSelect}>
|
||||
<div className="relative">
|
||||
<MagnifyingGlassIcon
|
||||
className="pointer-events-none absolute left-4 top-3.5 h-5 w-5 text-zinc-400"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Combobox.Input
|
||||
ref={inputRef}
|
||||
className="h-12 w-full border-0 bg-transparent pl-11 pr-4 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:ring-0 sm:text-sm font-medium"
|
||||
placeholder="O que você procura?"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
displayValue={(item: any) => item?.name}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredItems.length > 0 && (
|
||||
<Combobox.Options static className="max-h-[60vh] scroll-py-2 overflow-y-auto py-2 text-sm text-zinc-800 dark:text-zinc-200">
|
||||
{Object.entries(groups).map(([category, items]) => (
|
||||
<div key={category}>
|
||||
<div className="px-4 py-2 text-[10px] font-bold text-zinc-400 uppercase tracking-wider bg-zinc-50/50 dark:bg-zinc-800/50 mt-2 first:mt-0 mb-1">
|
||||
{category}
|
||||
</div>
|
||||
{items.map((item) => (
|
||||
<Combobox.Option
|
||||
key={item.href}
|
||||
value={item}
|
||||
className={({ active }) =>
|
||||
`cursor-pointer select-none px-4 py-2.5 transition-colors ${active
|
||||
? '[background:var(--gradient)] text-white'
|
||||
: ''
|
||||
}`
|
||||
}
|
||||
>
|
||||
{({ active }) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`flex h-8 w-8 items-center justify-center rounded-md ${active
|
||||
? 'bg-white/20 text-white'
|
||||
: 'bg-zinc-50 dark:bg-zinc-900 text-zinc-400'
|
||||
}`}>
|
||||
<item.icon
|
||||
className="h-4 w-4"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</div>
|
||||
<span className={`flex-auto truncate font-medium ${active ? 'text-white' : 'text-zinc-600 dark:text-zinc-400'}`}>
|
||||
{item.name}
|
||||
</span>
|
||||
{active && (
|
||||
<ArrowRightIcon className="h-4 w-4 text-white/70" />
|
||||
)}
|
||||
</div>
|
||||
{filteredItems.length > 0 && (
|
||||
<Combobox.Options static className="max-h-[60vh] scroll-py-2 overflow-y-auto py-2 text-sm text-zinc-800 dark:text-zinc-200">
|
||||
{Object.entries(groups).map(([category, items]) => (
|
||||
<div key={category}>
|
||||
<div className="px-4 py-2 text-[10px] font-bold text-zinc-400 uppercase tracking-wider bg-zinc-50/50 dark:bg-zinc-800/50 mt-2 first:mt-0 mb-1">
|
||||
{category}
|
||||
</div>
|
||||
{items.map((item) => (
|
||||
<Combobox.Option
|
||||
key={item.href}
|
||||
value={item}
|
||||
className={({ active }) =>
|
||||
`cursor-pointer select-none px-4 py-2.5 transition-colors ${active
|
||||
? '[background:var(--gradient)] text-white'
|
||||
: ''
|
||||
}`
|
||||
}
|
||||
>
|
||||
{({ active }) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`flex h-8 w-8 items-center justify-center rounded-md ${active
|
||||
? 'bg-white/20 text-white'
|
||||
: 'bg-zinc-50 dark:bg-zinc-900 text-zinc-400'
|
||||
}`}>
|
||||
<item.icon
|
||||
className="h-4 w-4"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</div>
|
||||
<span className={`flex-auto truncate font-medium ${active ? 'text-white' : 'text-zinc-600 dark:text-zinc-400'}`}>
|
||||
{item.name}
|
||||
</span>
|
||||
{active && (
|
||||
<ArrowRightIcon className="h-4 w-4 text-white/70" />
|
||||
)}
|
||||
</Combobox.Option>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Combobox.Option>
|
||||
))}
|
||||
</Combobox.Options>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Combobox.Options>
|
||||
)}
|
||||
|
||||
{query !== '' && filteredItems.length === 0 && (
|
||||
<div className="py-14 px-6 text-center text-sm sm:px-14">
|
||||
<MagnifyingGlassIcon className="mx-auto h-6 w-6 text-zinc-400" aria-hidden="true" />
|
||||
<p className="mt-4 font-semibold text-zinc-900 dark:text-white">Nenhum resultado encontrado</p>
|
||||
<p className="mt-2 text-zinc-500">Não conseguimos encontrar nada para "{query}". Tente buscar por páginas ou ações.</p>
|
||||
</div>
|
||||
)}
|
||||
{query !== '' && filteredItems.length === 0 && (
|
||||
<div className="py-14 px-6 text-center text-sm sm:px-14">
|
||||
<MagnifyingGlassIcon className="mx-auto h-6 w-6 text-zinc-400" aria-hidden="true" />
|
||||
<p className="mt-4 font-semibold text-zinc-900 dark:text-white">Nenhum resultado encontrado</p>
|
||||
<p className="mt-2 text-zinc-500">Não conseguimos encontrar nada para "{query}". Tente buscar por páginas ou ações.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between px-4 py-3 bg-zinc-50 dark:bg-zinc-900/50">
|
||||
<div className="flex gap-4 text-[10px] text-zinc-500 font-medium">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↵</kbd>
|
||||
Selecionar
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↓</kbd>
|
||||
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↑</kbd>
|
||||
Navegar
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[10px] text-zinc-500 font-medium">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<kbd className="flex h-5 w-auto px-1.5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">Esc</kbd>
|
||||
Fechar
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Combobox>
|
||||
</Dialog.Panel>
|
||||
</Transition.Child>
|
||||
</div>
|
||||
</Dialog>
|
||||
</Transition.Root>
|
||||
<div className="flex items-center justify-between px-4 py-3 bg-zinc-50 dark:bg-zinc-900/50">
|
||||
<div className="flex gap-4 text-[10px] text-zinc-500 font-medium">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↵</kbd>
|
||||
Selecionar
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↓</kbd>
|
||||
<kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↑</kbd>
|
||||
Navegar
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[10px] text-zinc-500 font-medium">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<kbd className="flex h-5 w-auto px-1.5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">Esc</kbd>
|
||||
Fechar
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Combobox>
|
||||
</DialogPanel>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { InputHTMLAttributes, forwardRef, useState } from "react";
|
||||
import { InputHTMLAttributes, forwardRef, useState, ReactNode } from "react";
|
||||
import { EyeIcon, EyeSlashIcon, ExclamationCircleIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||
label?: string;
|
||||
error?: string;
|
||||
helperText?: string;
|
||||
leftIcon?: string;
|
||||
rightIcon?: string;
|
||||
leftIcon?: ReactNode;
|
||||
rightIcon?: ReactNode;
|
||||
onRightIconClick?: () => void;
|
||||
}
|
||||
|
||||
@@ -41,26 +42,26 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
)}
|
||||
<div className="relative">
|
||||
{leftIcon && (
|
||||
<i
|
||||
className={`${leftIcon} absolute left-3.5 top-1/2 -translate-y-1/2 text-[#7D7D7D] dark:text-gray-400 text-[20px]`}
|
||||
/>
|
||||
<div className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#7D7D7D] dark:text-gray-400 w-5 h-5">
|
||||
{leftIcon}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
ref={ref}
|
||||
type={inputType}
|
||||
className={`
|
||||
w-full px-3.5 py-3 text-[14px] font-normal
|
||||
border rounded-md bg-white dark:bg-gray-700 dark:text-white
|
||||
placeholder:text-zinc-500 dark:placeholder:text-gray-400
|
||||
transition-all
|
||||
w-full px-4 py-2.5 text-sm font-normal
|
||||
border rounded-lg bg-white dark:bg-gray-800 dark:text-white
|
||||
placeholder:text-gray-400 dark:placeholder:text-gray-500
|
||||
transition-all duration-200
|
||||
${leftIcon ? "pl-11" : ""}
|
||||
${isPassword || rightIcon ? "pr-11" : ""}
|
||||
${error
|
||||
? "border-red-500 focus:border-red-500"
|
||||
: "border-zinc-200 dark:border-gray-600 focus:border-brand-500"
|
||||
? "border-red-500 focus:border-red-500 focus:ring-4 focus:ring-red-500/10"
|
||||
: "border-gray-200 dark:border-gray-700 focus:border-brand-500 focus:ring-4 focus:ring-brand-500/10"
|
||||
}
|
||||
outline-none ring-0 focus:ring-0 shadow-none focus:shadow-none
|
||||
disabled:bg-zinc-100 disabled:cursor-not-allowed
|
||||
outline-none
|
||||
disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed
|
||||
${className}
|
||||
`}
|
||||
{...props}
|
||||
@@ -71,9 +72,11 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3.5 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-900 transition-colors cursor-pointer"
|
||||
>
|
||||
<i
|
||||
className={`${showPassword ? "ri-eye-off-line" : "ri-eye-line"} text-[20px]`}
|
||||
/>
|
||||
{showPassword ? (
|
||||
<EyeSlashIcon className="w-5 h-5" />
|
||||
) : (
|
||||
<EyeIcon className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{!isPassword && rightIcon && (
|
||||
@@ -82,13 +85,13 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
onClick={onRightIconClick}
|
||||
className="absolute right-3.5 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-900 transition-colors cursor-pointer"
|
||||
>
|
||||
<i className={`${rightIcon} text-[20px]`} />
|
||||
<div className="w-5 h-5">{rightIcon}</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="mt-1 text-[13px] text-red-500 flex items-center gap-1">
|
||||
<i className="ri-error-warning-line" />
|
||||
<ExclamationCircleIcon className="w-4 h-4" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user