Skip to content

πŸ“š Documentazione del Progetto ​

Questa cartella contiene la documentazione completa del sistema di autenticazione e delle best practices per lo sviluppo.

🎯 BEST PRACTICES ⭐ ​

Guida completa alle best practices del progetto (aggiornata con TanStack Query):

  • βœ… Data Fetching con TanStack Query (raccomandato)
  • ❌ NO useRef per fetch in StrictMode
  • πŸ“¦ Import Policy (NO barrel files)
  • πŸ” Route Protection patterns
  • βš›οΈ React Compiler guidelines
  • πŸ§ͺ Testing patterns
  • πŸ”„ Multi-tab synchronization

πŸ‘‰ Leggi sempre questo documento prima di iniziare una nuova feature!


πŸ“– Contenuti ​

Autenticazione ​

Guida completa al sistema di autenticazione:

quick-start.md ​

Guida rapida per iniziare:

  • Come creare una pagina protetta
  • Come creare una pagina pubblica
  • Checklist complete
  • Best practices per API calls con TanStack Query
  • Note e convenzioni

πŸ“‘ TanStack Query (Data Fetching) ​

tanstack-query-guide.md ​

Guida completa e consolidata a TanStack Query v5:

  • βš™οΈ Configurazione e setup
  • πŸš€ Quick start (Query e Mutation)
  • πŸ“¦ Organizzazione file e hooks disponibili
  • 🎨 Pattern avanzati (conditional queries, filters, callbacks)
  • πŸ”„ Query keys e invalidazioni
  • 🎯 Best practices (NO useRef per fetch, import diretti)
  • πŸ§ͺ Testing con QueryClientProvider
  • πŸ”§ Creare nuovi moduli
  • πŸ› Troubleshooting

zustand-auth.md ​

Gestione dello stato con Zustand:

  • PerchΓ© Zustand
  • Struttura dello store
  • Persist middleware
  • Utilizzo nei componenti
  • Cross-tab synchronization

user-settings.md ​

Gestione delle impostazioni utente:

  • Caricamento automatico dei settings
  • Protezione route con requireSettings (verifica autenticazione + presenza settings)
  • Type guards per validazione
  • Accesso ai settings nei componenti

react-compiler-verification.md ​

Guida alla verifica di React Compiler:

  • Cosa ottimizza React Compiler
  • Pagina di test interattiva (/test-compiler)
  • Test con React DevTools Profiler
  • Analisi del bundle compilato
  • Metriche di successo e troubleshooting
  • Best practices con React Compiler

modules.md ​

Sistema di gestione moduli ERP:

  • Sidebar con lista moduli
  • Route dinamica per caricamento moduli
  • Iframe integration
  • Encoding/decoding dei path
  • Apertura in nuova tab

useBroadcastChannel.md ​

Documentazione dell'hook useBroadcastChannel:

  • Come funziona BroadcastChannel API
  • Esempi pratici di utilizzo
  • Confronto con storage events
  • Best practices

iframe-topbar-communication.md ​

Comunicazione Iframe - Topbar Menu:

  • Hook useTopbarMenu
  • Chiamate da iframe a parent per aggiornare il menu
  • Type declarations
  • Test e best practices

iframe-messages-communication.md ​

Comunicazione Iframe - Messages:

  • Hook useTopbarMessages
  • Store Zustand per persistenza stato
  • Gestione contatore messaggi non letti
  • Chiamate da iframe (readMessage, addMessage, setMessages)
  • Comportamento del modal automatico
  • Sincronizzazione cross-tab
  • Migrazione dal legacy Messages.js

iframe-navigation.md ​

Comunicazione Iframe - Navigation:

  • Hook useIframeNavigation
  • Navigazione dell'applicazione React dall'iframe
  • Chiamate da iframe per navigare (navigateTo)
  • Validazione e normalizzazione del path
  • Esempi di utilizzo e casi d'uso
  • Integrazione con React Router

iframe-toast-communication.md ​

Comunicazione Iframe - Toast:

  • Hook useToastBridge
  • Mostrare notifiche toast dall'iframe
  • Chiamate da iframe (show, success, info, warning, error, dismiss)
  • Varianti stilistiche dei toast
  • Esempi di utilizzo in PHP/JavaScript

error-boundary.md ​

Documentazione degli Error Boundary:

  • Come gestire gli errori a livello di route
  • Componente RouteErrorBoundary riutilizzabile
  • Errori HTTP (404, 401, 403, 500)
  • Personalizzazione e best practices

testing.md ​

Testing con Vitest:

  • Configurazione Vitest e React Testing Library
  • Test dei componenti
  • Test delle API
  • Coverage reports

zustand-migration.md (Archivio) ​

Migrazione a Zustand (storico):

  • Obiettivo della migrazione
  • File creati e modificati
  • Confronto prima/dopo
  • Benefici ottenuti

πŸš€ Inizio Rapido ​

Creare una Pagina Protetta con Data Fetching ​

  1. Registra la route in app/routes.ts:

    typescript
    route("dashboard", "routes/dashboard.tsx")
  2. Crea il file della route in app/routes/dashboard.tsx:

    typescript
    import { AuthenticatedLayout } from "@/components/layout/authenticated-layout";
    import { createProtectedLoader } from "@/lib/auth/loaders";
    import { useCompaniesList } from "@/hooks/api/auth/useAuthApi";
    
    // βœ… Una riga per proteggere
    export const clientLoader = createProtectedLoader();
    
    export default function Dashboard() {
        // βœ… TanStack Query - nessun useEffect/useRef necessario!
        const { data, isLoading } = useCompaniesList();
    
        return (
            <AuthenticatedLayout>
                <div>Dashboard con dati</div>
            </AuthenticatedLayout>
        );
    }

Una riga per proteggere, nessun flash di contenuto, zero boilerplate per fetch!

🎯 Concetti Chiave ​

Autenticazione ​

  • Factory functions: createProtectedLoader() e createGuestLoader()
  • Protezione pre-render: clientLoader blocca PRIMA del render
  • Zero flash: Nessun contenuto non autorizzato visibile
  • Type-safe: TypeScript verifica tutto
  • Multi-tab sync: Funziona automaticamente

Data Fetching (TanStack Query) ​

  • βœ… USA TanStack Query per chiamate API (raccomandato)
  • ❌ NO useRef per fetch - TanStack Query de-duplica automaticamente
  • Cache automatica: 5 minuti default, configurabile
  • StrictMode safe: Gestione automatica doppi render in dev
  • Import diretti: NO barrel files (index.ts)

πŸ“ Struttura del Progetto ​

app/
β”œβ”€β”€ routes.ts                       # Configurazione route
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ api.ts                      # Utility API (apiRequest, ApiError)
β”‚   β”œβ”€β”€ query-client.ts             # QueryClient TanStack Query
β”‚   └── auth/
β”‚       β”œβ”€β”€ auth.ts                 # Servizio di autenticazione
β”‚       └── loaders.ts              # Factory functions (createProtectedLoader, createGuestLoader)
β”œβ”€β”€ store/
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   └── auth.store.ts           # Zustand store autenticazione
β”‚   β”œβ”€β”€ cart/
β”‚   β”‚   └── cart.store.ts           # Zustand store carrello
β”‚   └── messages/
β”‚       └── messages.store.ts       # Zustand store messaggi
β”œβ”€β”€ api/
β”‚   └── auth/
β”‚       └── auth.api.ts             # Funzioni API autenticazione
β”œβ”€β”€ schemas/
β”‚   β”œβ”€β”€ api.schema.ts               # Schema base API
β”‚   └── auth/
β”‚       └── auth.schema.ts          # Schema autenticazione
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   └── auth/
β”‚   β”‚       └── useAuthApi.ts       # TanStack Query hooks per autenticazione
β”‚   β”œβ”€β”€ ui/
β”‚   β”‚   β”œβ”€β”€ useTopbarCart.ts        # Comunicazione carrello con iframe
β”‚   β”‚   └── useTopbarMessages.ts    # Comunicazione messaggi con iframe
β”‚   β”œβ”€β”€ sync/
β”‚   β”‚   β”œβ”€β”€ useBroadcastChannel.ts  # Hook per sincronizzazione multi-tab
β”‚   β”‚   β”œβ”€β”€ useAuthSyncListener.ts  # Sync autenticazione tra tab
β”‚   β”‚   β”œβ”€β”€ useCartSyncListener.ts  # Sync carrello tra tab
β”‚   β”‚   └── useMessagesSyncListener.ts # Sync messaggi tra tab
β”‚   └── iframe/
β”‚       └── useIframeNavigation.ts  # Navigazione dall'iframe
β”œβ”€β”€ components/
β”‚   └── layout/
β”‚       β”œβ”€β”€ authenticated-layout.tsx # Layout per pagine protette
β”‚       β”œβ”€β”€ sidebar/                # Componenti sidebar
β”‚       β”‚   β”œβ”€β”€ app-sidebar.tsx
β”‚       β”‚   β”œβ”€β”€ nav-modules.tsx
β”‚       β”‚   └── nav-user.tsx
β”‚       └── topbar/                 # Componenti topbar
β”‚           β”œβ”€β”€ cart.tsx
β”‚           β”œβ”€β”€ messages.tsx
β”‚           └── nav-actions.tsx
└── routes/
    β”œβ”€β”€ auth/
    β”‚   β”œβ”€β”€ login.tsx               # + createGuestLoader()
    β”‚   └── companies.tsx           # + createProtectedLoader()
    β”œβ”€β”€ welcome.tsx                 # + createProtectedLoader({ loadSettings: true })
    └── r.$path.tsx                 # Route moduli con iframe

πŸ’‘ Workflow Tipico ​

  1. Pianifica - Decidi quali route servono
  2. Registra - Aggiungile alla configurazione route in routes.ts
  3. Proteggi - Aggiungi clientLoader dove necessario
  4. Implementa - Scrivi il componente della pagina
  5. Testa - Il sistema gestisce autenticazione e sincronizzazione

πŸ”— Collegamenti Utili ​

❓ FAQ ​

Q: Devo aggiungere codice di autenticazione nelle route? A: Solo una riga: export const clientLoader = createProtectedLoader();

Q: Come faccio a sapere quali route sono protette? A: Cerca createProtectedLoader() nei file delle route.

Q: Funziona la sincronizzazione tra tab? A: Sì, automaticamente tramite AuthSyncListener.

Q: Posso avere route accessibili a tutti? A: Sì, semplicemente non aggiungere clientLoader.

Documentazione Elerama Frontend