Compare commits
37 Commits
69f475ec78
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1dc2f658a0 | ||
|
|
a3a641595d | ||
|
|
c2c922c1b7 | ||
|
|
894073644f | ||
|
|
26879acba4 | ||
|
|
92217897ca | ||
|
|
8eb7dfb00e | ||
|
|
eb24b86308 | ||
|
|
462a5a9383 | ||
|
|
c131343321 | ||
|
|
f3e65ee36f | ||
|
|
9eb1e0ddf5 | ||
|
|
04db2b30be | ||
|
|
644622f21c | ||
|
|
135782e54b | ||
|
|
6b5261f760 | ||
|
|
976dd95dc8 | ||
|
|
84338ea861 | ||
|
|
a22e4bf7b5 | ||
|
|
c7b86de3fb | ||
|
|
aa489c7eb8 | ||
|
|
3d24dfdeaf | ||
|
|
5aab19626f | ||
|
|
d0f530f757 | ||
|
|
96ba01b349 | ||
|
|
3c406ef405 | ||
|
|
9de40fde2d | ||
|
|
3a455e48d2 | ||
|
|
9205c4ef32 | ||
|
|
88cfe9af50 | ||
|
|
844294f7b2 | ||
|
|
b565895df1 | ||
|
|
ffb396a5a5 | ||
|
|
8c37e4bc50 | ||
|
|
a510d5fc68 | ||
|
|
702f50cc30 | ||
|
|
7def30702f |
41
.env
Normal file
41
.env
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# LogWhispererAI - Production Environment Configuration
|
||||||
|
# Generated for deployment with reverse proxy
|
||||||
|
# Date: 2026-04-03
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# FRONTEND CONFIGURATION (VITE_* variables)
|
||||||
|
# These are exposed to the browser
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# Backend API URL - HTTPS endpoint via reverse proxy
|
||||||
|
VITE_API_URL=https://srv-logwhispererai.lab.home.lucasacchi.net
|
||||||
|
|
||||||
|
# Webhook base URL - public HTTPS endpoint for webhooks
|
||||||
|
VITE_WEBHOOK_BASE_URL=https://logwhispererai.lab.home.lucasacchi.net/webhook
|
||||||
|
|
||||||
|
# Install script URL - public HTTPS endpoint for install script
|
||||||
|
VITE_INSTALL_SCRIPT_URL=https://logwhispererai.lab.home.lucasacchi.net/install.sh
|
||||||
|
|
||||||
|
# Application identification
|
||||||
|
VITE_APP_NAME=LogWhispererAI
|
||||||
|
|
||||||
|
# Application public URL - main frontend domain
|
||||||
|
VITE_APP_URL=https://logwhispererai.lab.home.lucasacchi.net
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# BACKEND CONFIGURATION
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# CORS Origins - restrict to frontend domain for security
|
||||||
|
# Only requests from this origin will be accepted by the backend
|
||||||
|
CORS_ORIGINS=https://logwhispererai.lab.home.lucasacchi.net
|
||||||
|
|
||||||
|
# Webhook base URL - used for generating webhook URLs
|
||||||
|
# This should match VITE_WEBHOOK_BASE_URL
|
||||||
|
WEBHOOK_BASE_URL=https://logwhispererai.lab.home.lucasacchi.net/webhook
|
||||||
|
|
||||||
|
# API delay simulation (milliseconds) - simulates AI processing time
|
||||||
|
DELAY_MS=1500
|
||||||
|
|
||||||
|
# Node environment
|
||||||
|
NODE_ENV=production
|
||||||
64
.env.example
Normal file
64
.env.example
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# LogWhispererAI - Environment Variables
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# FRONTEND CONFIGURATION (VITE_* variables)
|
||||||
|
# These are exposed to the browser
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# Backend API URL - where the frontend will make API calls
|
||||||
|
# Example: https://srv-logwhispererai.lab.home.lucasacchi.net
|
||||||
|
VITE_API_URL=http://localhost:3001
|
||||||
|
|
||||||
|
# Webhook base URL - used for displaying webhook URLs to users
|
||||||
|
# Example: https://logwhispererai.lab.home.lucasacchi.net/webhook
|
||||||
|
VITE_WEBHOOK_BASE_URL=http://localhost:3001/webhook
|
||||||
|
|
||||||
|
# Install script URL - the curl command shown to users
|
||||||
|
# Example: https://logwhispererai.lab.home.lucasacchi.net/install.sh
|
||||||
|
VITE_INSTALL_SCRIPT_URL=http://localhost:3001/install.sh
|
||||||
|
|
||||||
|
# Application identification
|
||||||
|
VITE_APP_NAME=LogWhispererAI
|
||||||
|
VITE_APP_URL=http://localhost:5173
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# BACKEND CONFIGURATION
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# CORS Origins - comma-separated list of allowed frontend origins
|
||||||
|
# Use '*' for development, set specific domains for production
|
||||||
|
# Example: https://logwhispererai.lab.home.lucasacchi.net
|
||||||
|
CORS_ORIGINS=*
|
||||||
|
|
||||||
|
# Webhook base URL - used for generating webhook URLs
|
||||||
|
# Example: https://logwhispererai.lab.home.lucasacchi.net/webhook
|
||||||
|
WEBHOOK_BASE_URL=https://logwhisperer.ai/webhook
|
||||||
|
|
||||||
|
# API delay simulation (milliseconds)
|
||||||
|
DELAY_MS=1500
|
||||||
|
|
||||||
|
# Node environment
|
||||||
|
NODE_ENV=development
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# OPTIONAL: Third-party Services
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# Telegram Bot Configuration
|
||||||
|
# TELEGRAM_BOT_TOKEN=your_bot_token_here
|
||||||
|
# TELEGRAM_CHAT_ID=your_chat_id_here
|
||||||
|
|
||||||
|
# n8n Configuration
|
||||||
|
# N8N_WEBHOOK_URL=https://your-n8n-instance.com/webhook/logwhisperer
|
||||||
|
|
||||||
|
# AI Provider Configuration
|
||||||
|
# OPENAI_API_KEY=your_openai_api_key_here
|
||||||
|
# ANTHROPIC_API_KEY=your_anthropic_api_key_here
|
||||||
|
|
||||||
|
# Supabase Configuration (per autenticazione e database)
|
||||||
|
# SUPABASE_URL=https://your-project.supabase.co
|
||||||
|
# SUPABASE_ANON_KEY=your_anon_key_here
|
||||||
|
|
||||||
|
# Stripe Configuration (per pagamenti)
|
||||||
|
# STRIPE_SECRET_KEY=sk_test_your_key_here
|
||||||
|
# STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here
|
||||||
13
.gitignore
vendored
13
.gitignore
vendored
@@ -20,3 +20,16 @@ htmlcov/
|
|||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
|
# OpenCode configuration with sensitive data
|
||||||
|
.opencode/opencode.json
|
||||||
|
|
||||||
|
# Telegram bot configuration (contains sensitive tokens)
|
||||||
|
docs/telegram_setup.md
|
||||||
|
|
||||||
|
# Frontend dependencies
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
frontend/.env
|
||||||
|
frontend/.env.local
|
||||||
|
frontend/.env.*.local
|
||||||
|
|||||||
36
.opencode/agents/bash-expert.md
Normal file
36
.opencode/agents/bash-expert.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Bash Expert Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
Lo Specialista Ingestion - Crea script di monitoraggio leggeri e sicuri per i server dei clienti.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Sviluppare script di `tail -f` e invio Webhook
|
||||||
|
- Garantire compatibilità POSIX
|
||||||
|
- Assicurare assenza di effetti collaterali sui server
|
||||||
|
- Ottimizzare per low footprint
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `bash` - Eseguire e testare script
|
||||||
|
- `write` - Creare script Bash
|
||||||
|
- `edit` - Modificare script esistenti
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Performance, portabilità, sicurezza server-side
|
||||||
|
|
||||||
|
## Safety Guidelines (Metodo Sacchi)
|
||||||
|
- **Read-only**: Mai scrivere sui log monitorati
|
||||||
|
- **No root escalation**: Funziona con permessi di lettura
|
||||||
|
- **Graceful degradation**: Salta file non accessibili
|
||||||
|
- **Rate limiting**: Previene flood di alert
|
||||||
|
|
||||||
|
## Script Requirements
|
||||||
|
- Shebang: `#!/bin/bash`
|
||||||
|
- `set -euo pipefail` per safety
|
||||||
|
- Nessuna credenziale hardcoded
|
||||||
|
- HTTPS obbligatorio per webhook
|
||||||
|
- Log di debug in `/var/log/logwhisperer/`
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
- Bash 4.0+
|
||||||
|
- POSIX-compliant dove possibile
|
||||||
|
- Dipendenze minime (curl, coreutils)
|
||||||
18
.opencode/agents/context_auditor_agent.md
Normal file
18
.opencode/agents/context_auditor_agent.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
description: Garante della documentazione aggiornata e prevenzione allucinazioni
|
||||||
|
mode: subagent
|
||||||
|
tools:
|
||||||
|
context7: true
|
||||||
|
read: true
|
||||||
|
sequential-thinking: true
|
||||||
|
|
||||||
|
@context-auditor
|
||||||
|
|
||||||
|
Il tuo scopo è garantire che ogni riga di codice prodotta dallo staff sia basata su documentazione reale e aggiornata.
|
||||||
|
|
||||||
|
Responsabilità
|
||||||
|
|
||||||
|
Eseguire ricerche semantiche tramite context7 su ogni nuova libreria introdotta.
|
||||||
|
|
||||||
|
Validare le proposte del @python-developer confrontandole con le API reali.
|
||||||
|
|
||||||
|
Utilizzare sequential-thinking per analizzare se una soluzione proposta è la più moderna ed efficiente disponibile.
|
||||||
55
.opencode/agents/documentation-agent.md
Normal file
55
.opencode/agents/documentation-agent.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
# Documentation Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
Il Cronista - Mantiene aggiornata la documentazione e il changelog.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Aggiornare `CHANGELOG.md` (Common Changelog)
|
||||||
|
- Scrivere commenti del codice e aggiornare file in `docs/`
|
||||||
|
- Curare qualità dei messaggi di commit
|
||||||
|
- Mantenere git history document
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `read` - Analizzare modifiche da documentare
|
||||||
|
- `write` - Creare documentazione
|
||||||
|
- `edit` - Aggiornare file esistenti
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Chiarezza, tracciabilità, consistenza
|
||||||
|
|
||||||
|
## Common Changelog Format
|
||||||
|
```markdown
|
||||||
|
## [Version] - YYYY-MM-DD
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Nuove feature
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Modifiche esistenti
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Bug fix
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- Fix sicurezza
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation Tasks
|
||||||
|
1. **CHANGELOG.md** - Dopo ogni feat/fix
|
||||||
|
2. **docs/specs/** - Specifiche tecniche
|
||||||
|
3. **docs/sprint*_verification.md** - Rapporti verifica
|
||||||
|
4. **docs/git-history.md** - Storia commit
|
||||||
|
5. **Inline comments** - Codice complesso
|
||||||
|
|
||||||
|
## Commit Message Quality
|
||||||
|
- Formato: `tipo(scope): descrizione`
|
||||||
|
- Tipi: feat, fix, docs, test, refactor, chore
|
||||||
|
- Descrizione al presente imperativo
|
||||||
|
- Max 50 caratteri soggetto
|
||||||
|
- Body opzionale per dettagli
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
1. Identifica modifiche da documentare
|
||||||
|
2. Aggiorna CHANGELOG.md
|
||||||
|
3. Aggiorna docs/ se necessario
|
||||||
|
4. Commit con messaggio descrittivo
|
||||||
18
.opencode/agents/n8n_specialist_agent.md
Normal file
18
.opencode/agents/n8n_specialist_agent.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
description: Esperto in automazione e orchestrazione n8n
|
||||||
|
mode: subagent
|
||||||
|
tools:
|
||||||
|
n8n: true
|
||||||
|
bash: true
|
||||||
|
read: true
|
||||||
|
|
||||||
|
@n8n-specialist
|
||||||
|
|
||||||
|
Sei un esperto di automazione n8n. Il tuo compito è interfacciare LogWhispererAI con l'istanza Docker su 192.168.254.12.
|
||||||
|
|
||||||
|
Focus Operativo
|
||||||
|
|
||||||
|
Configurazione e testing dei Webhook di ricezione log.
|
||||||
|
|
||||||
|
Monitoraggio delle esecuzioni per garantire che il "Metodo Sacchi" venga applicato nei prompt dell'LLM interno a n8n.
|
||||||
|
|
||||||
|
Troubleshooting della connessione tra lo script Bash locale e l'API di n8n.
|
||||||
28
.opencode/agents/product-manager.md
Normal file
28
.opencode/agents/product-manager.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Product Manager Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
Il Garante del Valore - Assicura che ogni feature contribuisca alla UVP e all'Activation Rate.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Monitorare il file `docs/prd.md`
|
||||||
|
- Identificare ed eliminare le "vanity features"
|
||||||
|
- Gestire la roadmap degli Sprint
|
||||||
|
- Definire priorità e scope dei task
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `read` - Analizzare PRD e documentazione
|
||||||
|
- `write` - Solo per documentazione (prd.md, roadmap)
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Business logic, priorità, value proposition
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
1. Definisce obiettivo del task/sprint
|
||||||
|
2. Aggiorna PRD se necessario
|
||||||
|
3. Coordina con Tech Lead per specifiche
|
||||||
|
4. Valida che l'output risolva il problema utente
|
||||||
|
|
||||||
|
## Key Metrics
|
||||||
|
- UVP (Unique Value Proposition) alignment
|
||||||
|
- Activation Rate improvement
|
||||||
|
- Scope control (no scope creep)
|
||||||
37
.opencode/agents/python-developer.md
Normal file
37
.opencode/agents/python-developer.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Python Developer Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
Il Costruttore TDD - Implementa la logica core in Python seguendo rigorosamente il TDD.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Scrivere codice pulito (PEP8) nel venv
|
||||||
|
- Implementare feature solo dopo che i test di QA Engineer sono pronti
|
||||||
|
- Gestire Conventional Commits
|
||||||
|
- Ottimizzare performance e leggibilità
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `write` - Creare file Python
|
||||||
|
- `edit` - Modificare codice esistente
|
||||||
|
- `bash` - Eseguire comandi pip/venv
|
||||||
|
- `lsp` - Language server protocol per refactoring
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Implementazione, qualità codice, TDD
|
||||||
|
|
||||||
|
## Workflow (TDD)
|
||||||
|
1. Riceve specifica da Tech Lead
|
||||||
|
2. Attende test da QA Engineer (RED phase)
|
||||||
|
3. Scrive codice minimo per far passare i test (GREEN phase)
|
||||||
|
4. Refactor mantenendo test verdi
|
||||||
|
|
||||||
|
## Standards
|
||||||
|
- PEP8 compliance
|
||||||
|
- Type hints dove appropriato
|
||||||
|
- Docstring per funzioni pubbliche
|
||||||
|
- Conventional commits (feat:, fix:, refactor:)
|
||||||
|
|
||||||
|
## Virtual Environment
|
||||||
|
```bash
|
||||||
|
source venv/bin/activate
|
||||||
|
python -m pytest
|
||||||
|
```
|
||||||
46
.opencode/agents/qa-engineer.md
Normal file
46
.opencode/agents/qa-engineer.md
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
# QA Engineer Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
Il Tester - Garantisce che il software sia privo di bug e resiliente.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Scrivere test unitari e di integrazione (Pytest)
|
||||||
|
- Simulare errori di log per testare la pipeline n8n
|
||||||
|
- Verificare che i test falliscano prima dell'implementazione (Red phase)
|
||||||
|
- Mantenere copertura test delle feature critiche
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `bash` - Eseguire pytest
|
||||||
|
- `read` - Analizzare codice da testare
|
||||||
|
- `write` - Creare file di test
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Copertura test, regressioni, affidabilità
|
||||||
|
|
||||||
|
## TDD Workflow
|
||||||
|
1. **RED**: Scrive test che fallisce (prima dell'implementazione)
|
||||||
|
2. Conferma con: `pytest tests/test_feature.py -v` → FAIL
|
||||||
|
3. Passa a Developer per implementazione
|
||||||
|
4. **GREEN**: Verifica che test passi dopo implementazione
|
||||||
|
|
||||||
|
## Test Standards
|
||||||
|
- Nomi descrittivi: `test_descrizione_comportamento`
|
||||||
|
- Un assert per test (idealmente)
|
||||||
|
- Fixture pytest per setup/teardown
|
||||||
|
- Parametrizzazione per casi multipli
|
||||||
|
|
||||||
|
## Test Categories
|
||||||
|
1. **Unit Tests** - Funzioni isolate
|
||||||
|
2. **Integration Tests** - Componenti insieme
|
||||||
|
3. **E2E Tests** - Flusso completo
|
||||||
|
|
||||||
|
## Coverage Targets
|
||||||
|
- Feature critiche: 100%
|
||||||
|
- Feature standard: 80%+
|
||||||
|
- Utils: 60%+
|
||||||
|
|
||||||
|
## Running Tests
|
||||||
|
```bash
|
||||||
|
source venv/bin/activate
|
||||||
|
pytest tests/ -v --cov=src --cov-report=html
|
||||||
|
```
|
||||||
44
.opencode/agents/security-auditor.md
Normal file
44
.opencode/agents/security-auditor.md
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
# Security Auditor Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
Il Guardiano - Verifica la sicurezza degli script e dei flussi di dati.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Analizzare script Bash per prevenire Command Injection
|
||||||
|
- Verificare gestione sicura di API Key e Webhook URL
|
||||||
|
- Applicare il principio "Safety First"
|
||||||
|
- Audit configurazioni e permessi
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `read` - Analizzare codice sorgente
|
||||||
|
- `grep` - Cercare pattern insicuri
|
||||||
|
- `bash` - Eseguire strumenti di linting/security
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Vulnerabilità, protezione dati, compliance sicurezza
|
||||||
|
|
||||||
|
## Security Checklist
|
||||||
|
|
||||||
|
### Script Bash
|
||||||
|
- [ ] No eval su input utente
|
||||||
|
- [ ] Quote variabili: `"$variable"` non `$variable`
|
||||||
|
- [ ] Validazione input prima di uso
|
||||||
|
- [ ] No credenziali in codice sorgente
|
||||||
|
- [ ] Permessi file corretti (600 per config)
|
||||||
|
|
||||||
|
### API & Webhook
|
||||||
|
- [ ] HTTPS obbligatorio
|
||||||
|
- [ ] Validazione URL
|
||||||
|
- [ ] Header Content-Type corretto
|
||||||
|
- [ ] No logging di dati sensibili
|
||||||
|
|
||||||
|
### Dati
|
||||||
|
- [ ] CLIENT_ID come UUID v4
|
||||||
|
- [ ] Nessun dato PII nei log
|
||||||
|
- [ ] Sanitizzazione log prima di invio
|
||||||
|
|
||||||
|
## Common Vulnerabilities to Check
|
||||||
|
1. Command Injection
|
||||||
|
2. Path Traversal
|
||||||
|
3. Information Disclosure
|
||||||
|
4. Insecure Permissions
|
||||||
30
.opencode/agents/tech-lead.md
Normal file
30
.opencode/agents/tech-lead.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Tech Lead Agent Configuration
|
||||||
|
|
||||||
|
## Role
|
||||||
|
L'Architetto - Responsabile dell'integrità tecnica e della coerenza con il PRD.
|
||||||
|
|
||||||
|
## Responsibilities
|
||||||
|
- Validare le specifiche tecniche in `docs/specs/` prima dell'implementazione
|
||||||
|
- Verificare che l'architettura rispetti il "Metodo Sacchi"
|
||||||
|
- Coordinare i passaggi tra gli altri agenti
|
||||||
|
- Revisionare il codice per conformità architetturale
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
- `read` - Analizzare PRD e specifiche
|
||||||
|
- `list` - Esplorare struttura progetto
|
||||||
|
- `grep` - Cercare pattern nel codice
|
||||||
|
- `edit` - Modificare specifiche se necessario
|
||||||
|
|
||||||
|
## Focus
|
||||||
|
Architettura, conformità, qualità del design
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
1. Riceve task dal Product Manager
|
||||||
|
2. Scrive/valida specifica tecnica in `docs/specs/`
|
||||||
|
3. Coordina Developer e QA Engineer
|
||||||
|
4. Fa review finale prima del merge
|
||||||
|
|
||||||
|
## Metodo Sacchi Checklist
|
||||||
|
- [ ] Architecture safety first
|
||||||
|
- [ ] Modular design (little often)
|
||||||
|
- [ ] Double check requirements coverage
|
||||||
11
.opencode/skills/Git_and_Changelog/SKILL.md
Normal file
11
.opencode/skills/Git_and_Changelog/SKILL.md
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
Skill: Git & Changelog Manager
|
||||||
|
|
||||||
|
Istruzioni per la gestione dei commit e del versionamento.
|
||||||
|
|
||||||
|
Standard
|
||||||
|
|
||||||
|
Conventional Commits: Ogni commit deve iniziare con feat:, fix:, docs:, test:, refactor:, chore:.
|
||||||
|
|
||||||
|
Atomic Commits: Un commit per ogni singola modifica funzionale.
|
||||||
|
|
||||||
|
Common Changelog: Dopo ogni feat o fix, aggiorna CHANGELOG.md nella sezione [Unreleased] o nella versione corrente.
|
||||||
775
.opencode/skills/SKILL.md
Normal file
775
.opencode/skills/SKILL.md
Normal file
@@ -0,0 +1,775 @@
|
|||||||
|
---
|
||||||
|
name: frontend_engineer
|
||||||
|
description: Frontend development for RetentionAI dashboard. Use this skill when working on: (1) Next.js 14 App Router components, (2) Dashboard UI and data visualization, (3) Real-time updates (WebSocket), (4) Form handling and validation, (5) TypeScript interfaces, (6) Tailwind CSS styling with Shadcn/UI, (7) API integration with React Query.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Frontend Engineer Skill
|
||||||
|
|
||||||
|
## Next.js 14 Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/
|
||||||
|
├── app/
|
||||||
|
│ ├── (auth)/ # Auth routes
|
||||||
|
│ │ └── login/
|
||||||
|
│ ├── dashboard/ # Main dashboard
|
||||||
|
│ │ ├── page.tsx # Executive view
|
||||||
|
│ │ ├── campaigns/ # Campaign manager
|
||||||
|
│ │ ├── customers/ # Customer explorer
|
||||||
|
│ │ └── health/ # Data quality
|
||||||
|
│ ├── layout.tsx # Root layout
|
||||||
|
│ └── globals.css
|
||||||
|
├── components/
|
||||||
|
│ ├── ui/ # Shadcn components
|
||||||
|
│ ├── charts/ # Recharts wrappers
|
||||||
|
│ ├── EventFeed.tsx
|
||||||
|
│ ├── MetricsCard.tsx
|
||||||
|
│ └── RiskHeatmap.tsx
|
||||||
|
├── lib/
|
||||||
|
│ ├── api-client.ts # Backend API wrapper
|
||||||
|
│ ├── hooks.ts # Custom React hooks
|
||||||
|
│ └── utils.ts
|
||||||
|
├── package.json
|
||||||
|
└── tsconfig.json
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dashboard Page (Server Component)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/dashboard/page.tsx
|
||||||
|
import { MetricsCard } from '@/components/MetricsCard'
|
||||||
|
import { EventFeed } from '@/components/EventFeed'
|
||||||
|
import { RiskHeatmap } from '@/components/RiskHeatmap'
|
||||||
|
|
||||||
|
export default async function DashboardPage() {
|
||||||
|
// Fetch data on server (Next.js 14 pattern)
|
||||||
|
const metrics = await fetchMetrics()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container mx-auto p-6 space-y-6">
|
||||||
|
{/* KPI Cards */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
|
<MetricsCard
|
||||||
|
title="At-Risk Revenue"
|
||||||
|
value={metrics.atRiskRevenue}
|
||||||
|
format="currency"
|
||||||
|
trend={metrics.atRiskTrend}
|
||||||
|
/>
|
||||||
|
<MetricsCard
|
||||||
|
title="Saved Revenue"
|
||||||
|
value={metrics.savedRevenue}
|
||||||
|
format="currency"
|
||||||
|
trend={metrics.savedTrend}
|
||||||
|
/>
|
||||||
|
<MetricsCard
|
||||||
|
title="Campaign ROI"
|
||||||
|
value={metrics.campaignRoi}
|
||||||
|
format="percentage"
|
||||||
|
trend={metrics.roiTrend}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main Content */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
|
{/* Live Event Feed */}
|
||||||
|
<EventFeed initialEvents={metrics.recentEvents} />
|
||||||
|
|
||||||
|
{/* Risk Heatmap */}
|
||||||
|
<RiskHeatmap data={metrics.cohortRisks} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchMetrics() {
|
||||||
|
// Server-side data fetching
|
||||||
|
const res = await fetch('http://localhost:8000/api/metrics', {
|
||||||
|
cache: 'no-store', // Always fresh
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${process.env.API_KEY}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) throw new Error('Failed to fetch metrics')
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Metrics Card Component
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/MetricsCard.tsx
|
||||||
|
import { TrendingUp, TrendingDown } from 'lucide-react'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
|
||||||
|
interface MetricsCardProps {
|
||||||
|
title: string
|
||||||
|
value: number
|
||||||
|
format: 'currency' | 'percentage' | 'number'
|
||||||
|
trend?: { value: number; direction: 'up' | 'down' }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MetricsCard({ title, value, format, trend }: MetricsCardProps) {
|
||||||
|
const formattedValue = formatValue(value, format)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||||
|
{title}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-3xl font-bold">{formattedValue}</div>
|
||||||
|
|
||||||
|
{trend && (
|
||||||
|
<div className="flex items-center gap-1 text-sm mt-2">
|
||||||
|
{trend.direction === 'up' ? (
|
||||||
|
<TrendingUp className="h-4 w-4 text-green-500" />
|
||||||
|
) : (
|
||||||
|
<TrendingDown className="h-4 w-4 text-red-500" />
|
||||||
|
)}
|
||||||
|
<span className={trend.direction === 'up' ? 'text-green-500' : 'text-red-500'}>
|
||||||
|
{Math.abs(trend.value)}%
|
||||||
|
</span>
|
||||||
|
<span className="text-muted-foreground">vs last week</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatValue(value: number, format: MetricsCardProps['format']): string {
|
||||||
|
switch (format) {
|
||||||
|
case 'currency':
|
||||||
|
return new Intl.NumberFormat('en-US', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'USD',
|
||||||
|
minimumFractionDigits: 0,
|
||||||
|
maximumFractionDigits: 0
|
||||||
|
}).format(value)
|
||||||
|
|
||||||
|
case 'percentage':
|
||||||
|
return `${(value * 100).toFixed(1)}%`
|
||||||
|
|
||||||
|
case 'number':
|
||||||
|
return new Intl.NumberFormat('en-US').format(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Live Event Feed (Client Component)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/EventFeed.tsx
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { formatDistanceToNow } from 'date-fns'
|
||||||
|
|
||||||
|
interface Event {
|
||||||
|
id: string
|
||||||
|
type: string
|
||||||
|
customer_email: string
|
||||||
|
timestamp: string
|
||||||
|
properties: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EventFeedProps {
|
||||||
|
initialEvents?: Event[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventFeed({ initialEvents = [] }: EventFeedProps) {
|
||||||
|
const [events, setEvents] = useState<Event[]>(initialEvents)
|
||||||
|
|
||||||
|
// Poll for new events every 5 seconds
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: ['events'],
|
||||||
|
queryFn: fetchEvents,
|
||||||
|
refetchInterval: 5000,
|
||||||
|
initialData: initialEvents
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (data) setEvents(data)
|
||||||
|
}, [data])
|
||||||
|
|
||||||
|
// WebSocket for real-time updates (optional enhancement)
|
||||||
|
useEffect(() => {
|
||||||
|
const ws = new WebSocket('ws://localhost:8000/ws/events')
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const newEvent = JSON.parse(event.data)
|
||||||
|
setEvents(prev => [newEvent, ...prev].slice(0, 20)) // Keep last 20
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => ws.close()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Live Event Stream</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-2 max-h-[500px] overflow-y-auto">
|
||||||
|
{events.map(event => (
|
||||||
|
<div
|
||||||
|
key={event.id}
|
||||||
|
className="flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant={getEventVariant(event.type)}>
|
||||||
|
{event.type}
|
||||||
|
</Badge>
|
||||||
|
<span className="text-sm font-medium">
|
||||||
|
{event.customer_email}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
{formatDistanceToNow(new Date(event.timestamp), { addSuffix: true })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{event.type === 'payment_failed' && (
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="text-sm font-bold text-destructive">
|
||||||
|
${(event.properties.amount / 100).toFixed(2)}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{event.properties.failure_code}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchEvents(): Promise<Event[]> {
|
||||||
|
const res = await fetch('/api/events/recent')
|
||||||
|
if (!res.ok) throw new Error('Failed to fetch events')
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
function getEventVariant(eventType: string): 'default' | 'destructive' | 'secondary' {
|
||||||
|
switch (eventType) {
|
||||||
|
case 'payment_failed':
|
||||||
|
return 'destructive'
|
||||||
|
case 'subscription_cancelled':
|
||||||
|
return 'destructive'
|
||||||
|
case 'purchase':
|
||||||
|
return 'default'
|
||||||
|
default:
|
||||||
|
return 'secondary'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risk Heatmap (Recharts)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/RiskHeatmap.tsx
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import {
|
||||||
|
ResponsiveContainer,
|
||||||
|
ScatterChart,
|
||||||
|
Scatter,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
ZAxis,
|
||||||
|
Tooltip,
|
||||||
|
Cell
|
||||||
|
} from 'recharts'
|
||||||
|
|
||||||
|
interface CohortData {
|
||||||
|
month: string
|
||||||
|
cohortSize: number
|
||||||
|
churnRisk: number // 0-1
|
||||||
|
revenue: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RiskHeatmapProps {
|
||||||
|
data: CohortData[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RiskHeatmap({ data }: RiskHeatmapProps) {
|
||||||
|
// Color scale based on churn risk
|
||||||
|
const getColor = (risk: number) => {
|
||||||
|
if (risk > 0.7) return '#ef4444' // red
|
||||||
|
if (risk > 0.4) return '#f97316' // orange
|
||||||
|
if (risk > 0.2) return '#eab308' // yellow
|
||||||
|
return '#22c55e' // green
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Cohort Risk Analysis</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ResponsiveContainer width="100%" height={400}>
|
||||||
|
<ScatterChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
|
||||||
|
<XAxis
|
||||||
|
type="number"
|
||||||
|
dataKey="cohortSize"
|
||||||
|
name="Cohort Size"
|
||||||
|
label={{ value: 'Cohort Size', position: 'insideBottom', offset: -10 }}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
type="number"
|
||||||
|
dataKey="churnRisk"
|
||||||
|
name="Churn Risk"
|
||||||
|
label={{ value: 'Churn Risk', angle: -90, position: 'insideLeft' }}
|
||||||
|
domain={[0, 1]}
|
||||||
|
/>
|
||||||
|
<ZAxis
|
||||||
|
type="number"
|
||||||
|
dataKey="revenue"
|
||||||
|
range={[100, 1000]}
|
||||||
|
name="Revenue"
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
cursor={{ strokeDasharray: '3 3' }}
|
||||||
|
content={({ active, payload }) => {
|
||||||
|
if (!active || !payload?.[0]) return null
|
||||||
|
|
||||||
|
const data = payload[0].payload as CohortData
|
||||||
|
return (
|
||||||
|
<div className="bg-background border rounded-lg p-3 shadow-lg">
|
||||||
|
<p className="font-semibold">{data.month}</p>
|
||||||
|
<p className="text-sm">Size: {data.cohortSize} customers</p>
|
||||||
|
<p className="text-sm">Risk: {(data.churnRisk * 100).toFixed(1)}%</p>
|
||||||
|
<p className="text-sm">Revenue: ${data.revenue.toLocaleString()}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Scatter data={data}>
|
||||||
|
{data.map((entry, index) => (
|
||||||
|
<Cell key={index} fill={getColor(entry.churnRisk)} />
|
||||||
|
))}
|
||||||
|
</Scatter>
|
||||||
|
</ScatterChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API Client (React Query)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// lib/api-client.ts
|
||||||
|
import { QueryClient } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
export const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||||
|
retry: 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
|
||||||
|
|
||||||
|
export async function apiClient<T>(
|
||||||
|
endpoint: string,
|
||||||
|
options?: RequestInit
|
||||||
|
): Promise<T> {
|
||||||
|
const res = await fetch(`${API_URL}${endpoint}`, {
|
||||||
|
...options,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...options?.headers
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const error = await res.json().catch(() => ({ message: 'Unknown error' }))
|
||||||
|
throw new Error(error.message || `HTTP ${res.status}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
// API methods
|
||||||
|
export const api = {
|
||||||
|
// Metrics
|
||||||
|
getMetrics: () => apiClient<Metrics>('/api/metrics'),
|
||||||
|
|
||||||
|
// Events
|
||||||
|
getRecentEvents: () => apiClient<Event[]>('/api/events/recent'),
|
||||||
|
|
||||||
|
// Customers
|
||||||
|
getCustomer: (id: string) => apiClient<Customer>(`/api/customers/${id}`),
|
||||||
|
searchCustomers: (query: string) =>
|
||||||
|
apiClient<Customer[]>(`/api/customers/search?q=${query}`),
|
||||||
|
|
||||||
|
// Predictions
|
||||||
|
getCustomerPredictions: (customerId: string) =>
|
||||||
|
apiClient<Prediction[]>(`/api/predictions/${customerId}`),
|
||||||
|
|
||||||
|
// Campaigns
|
||||||
|
getCampaigns: () => apiClient<Campaign[]>('/api/campaigns'),
|
||||||
|
createCampaign: (data: CampaignCreate) =>
|
||||||
|
apiClient<Campaign>('/api/campaigns', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Custom Hooks
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// lib/hooks.ts
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api } from './api-client'
|
||||||
|
|
||||||
|
// Metrics hook
|
||||||
|
export function useMetrics() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['metrics'],
|
||||||
|
queryFn: api.getMetrics,
|
||||||
|
refetchInterval: 30000 // Refresh every 30s
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Customer search hook
|
||||||
|
export function useCustomerSearch(query: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['customers', 'search', query],
|
||||||
|
queryFn: () => api.searchCustomers(query),
|
||||||
|
enabled: query.length > 2 // Only search if 3+ characters
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Campaign creation hook
|
||||||
|
export function useCreateCampaign() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: api.createCampaign,
|
||||||
|
onSuccess: () => {
|
||||||
|
// Invalidate campaigns list
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Form Handling (Zod + React Hook Form)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/dashboard/campaigns/create/page.tsx
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger } from '@/components/ui/select'
|
||||||
|
import { useCreateCampaign } from '@/lib/hooks'
|
||||||
|
|
||||||
|
const campaignSchema = z.object({
|
||||||
|
name: z.string().min(3, 'Name must be at least 3 characters'),
|
||||||
|
segment: z.enum(['persuadable', 'sure_thing', 'all']),
|
||||||
|
offerType: z.enum(['10_percent_off', 'free_shipping', 'bogo', 'vip_access']),
|
||||||
|
channel: z.enum(['email', 'sms'])
|
||||||
|
})
|
||||||
|
|
||||||
|
type CampaignForm = z.infer<typeof campaignSchema>
|
||||||
|
|
||||||
|
export default function CreateCampaignPage() {
|
||||||
|
const createCampaign = useCreateCampaign()
|
||||||
|
|
||||||
|
const { register, handleSubmit, formState: { errors } } = useForm<CampaignForm>({
|
||||||
|
resolver: zodResolver(campaignSchema)
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmit = async (data: CampaignForm) => {
|
||||||
|
await createCampaign.mutateAsync(data)
|
||||||
|
// Redirect or show success message
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container max-w-2xl py-8">
|
||||||
|
<h1 className="text-3xl font-bold mb-6">Create Campaign</h1>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">Campaign Name</label>
|
||||||
|
<Input {...register('name')} placeholder="Winback Campaign Q1" />
|
||||||
|
{errors.name && (
|
||||||
|
<p className="text-sm text-destructive mt-1">{errors.name.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">Target Segment</label>
|
||||||
|
<Select {...register('segment')}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<span>Select segment</span>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="persuadable">Persuadables Only</SelectItem>
|
||||||
|
<SelectItem value="sure_thing">Sure Things</SelectItem>
|
||||||
|
<SelectItem value="all">All Customers</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">Offer Type</label>
|
||||||
|
<Select {...register('offerType')}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<span>Select offer</span>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="10_percent_off">10% Discount</SelectItem>
|
||||||
|
<SelectItem value="free_shipping">Free Shipping</SelectItem>
|
||||||
|
<SelectItem value="bogo">Buy One Get One</SelectItem>
|
||||||
|
<SelectItem value="vip_access">VIP Early Access</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button type="submit" disabled={createCampaign.isPending}>
|
||||||
|
{createCampaign.isPending ? 'Creating...' : 'Create Campaign'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Styling with Tailwind + Shadcn
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Example of consistent styling patterns
|
||||||
|
|
||||||
|
// Card pattern
|
||||||
|
<Card className="p-6">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Title</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>Content</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
// Button variants
|
||||||
|
<Button>Default</Button>
|
||||||
|
<Button variant="destructive">Delete</Button>
|
||||||
|
<Button variant="outline">Cancel</Button>
|
||||||
|
<Button variant="ghost">Icon only</Button>
|
||||||
|
|
||||||
|
// Badge variants
|
||||||
|
<Badge>Default</Badge>
|
||||||
|
<Badge variant="destructive">Error</Badge>
|
||||||
|
<Badge variant="secondary">Info</Badge>
|
||||||
|
|
||||||
|
// Colors (use Tailwind classes)
|
||||||
|
- Primary: bg-primary text-primary-foreground
|
||||||
|
- Destructive: bg-destructive text-destructive-foreground
|
||||||
|
- Success: bg-green-500 text-white
|
||||||
|
- Warning: bg-yellow-500 text-black
|
||||||
|
- Info: bg-blue-500 text-white
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TypeScript Interfaces
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// lib/types.ts
|
||||||
|
|
||||||
|
export interface Metrics {
|
||||||
|
atRiskRevenue: number
|
||||||
|
savedRevenue: number
|
||||||
|
campaignRoi: number
|
||||||
|
atRiskTrend: { value: number; direction: 'up' | 'down' }
|
||||||
|
savedTrend: { value: number; direction: 'up' | 'down' }
|
||||||
|
roiTrend: { value: number; direction: 'up' | 'down' }
|
||||||
|
recentEvents: Event[]
|
||||||
|
cohortRisks: CohortData[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Event {
|
||||||
|
id: string
|
||||||
|
type: string
|
||||||
|
customer_email: string
|
||||||
|
timestamp: string
|
||||||
|
properties: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Customer {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
totalRevenue: number
|
||||||
|
purchaseCount: number
|
||||||
|
lastPurchaseAt: string
|
||||||
|
customAttributes: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Prediction {
|
||||||
|
id: string
|
||||||
|
type: 'clv' | 'churn_risk' | 'uplift'
|
||||||
|
value: number
|
||||||
|
segment?: 'persuadable' | 'sure_thing' | 'lost_cause'
|
||||||
|
confidence: number
|
||||||
|
predictedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Campaign {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
segment: string
|
||||||
|
offerType: string
|
||||||
|
status: 'active' | 'paused' | 'completed'
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CampaignCreate {
|
||||||
|
name: string
|
||||||
|
segment: string
|
||||||
|
offerType: string
|
||||||
|
channel: string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing Components
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/__tests__/MetricsCard.test.tsx
|
||||||
|
import { render, screen } from '@testing-library/react'
|
||||||
|
import { MetricsCard } from '../MetricsCard'
|
||||||
|
|
||||||
|
describe('MetricsCard', () => {
|
||||||
|
it('renders currency value correctly', () => {
|
||||||
|
render(
|
||||||
|
<MetricsCard
|
||||||
|
title="At-Risk Revenue"
|
||||||
|
value={125000}
|
||||||
|
format="currency"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getByText('At-Risk Revenue')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText('$125,000')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders percentage value correctly', () => {
|
||||||
|
render(
|
||||||
|
<MetricsCard
|
||||||
|
title="Campaign ROI"
|
||||||
|
value={0.456}
|
||||||
|
format="percentage"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getByText('45.6%')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows trend indicator', () => {
|
||||||
|
render(
|
||||||
|
<MetricsCard
|
||||||
|
title="Test"
|
||||||
|
value={100}
|
||||||
|
format="number"
|
||||||
|
trend={{ value: 12.5, direction: 'up' }}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.getByText('12.5%')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/vs last week/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Performance Optimization
|
||||||
|
|
||||||
|
### 1. Use Server Components by Default
|
||||||
|
```tsx
|
||||||
|
// Default: Server Component (no 'use client')
|
||||||
|
export default async function Page() {
|
||||||
|
const data = await fetchData() // Fetched on server
|
||||||
|
return <div>{data}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Client Components Only When Needed
|
||||||
|
```tsx
|
||||||
|
// Use 'use client' for interactivity
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
export function InteractiveComponent() {
|
||||||
|
const [state, setState] = useState()
|
||||||
|
// ... interactive logic
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Image Optimization
|
||||||
|
```tsx
|
||||||
|
import Image from 'next/image'
|
||||||
|
|
||||||
|
<Image
|
||||||
|
src="/logo.png"
|
||||||
|
alt="RetentionAI"
|
||||||
|
width={200}
|
||||||
|
height={50}
|
||||||
|
priority // For above-the-fold images
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Dynamic Imports (Code Splitting)
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
|
||||||
|
loading: () => <p>Loading chart...</p>,
|
||||||
|
ssr: false // Don't render on server
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
- Use Next.js 14 App Router (Server Components by default)
|
||||||
|
- Tailwind CSS + Shadcn/UI for consistent styling
|
||||||
|
- React Query for server state management
|
||||||
|
- Zod + React Hook Form for type-safe forms
|
||||||
|
- Recharts for data visualization
|
||||||
|
- TypeScript strict mode for type safety
|
||||||
|
- Component testing with Vitest
|
||||||
17
.opencode/skills/TDD_Python_Specialist/SKILL.md
Normal file
17
.opencode/skills/TDD_Python_Specialist/SKILL.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
Skill: TDD Python Specialist
|
||||||
|
|
||||||
|
Questo playbook istruisce l'agente su come operare in modalità TDD.
|
||||||
|
|
||||||
|
Workflow Obbligatorio
|
||||||
|
|
||||||
|
Red: Crea un file in tests/test_feature.py. Definisci il test. Eseguilo con pytest e conferma il fallimento.
|
||||||
|
|
||||||
|
Green: Scrivi il codice minimo necessario in scripts/ o nella root per far passare il test.
|
||||||
|
|
||||||
|
Refactor: Ottimizza il codice mantenendo i test verdi.
|
||||||
|
|
||||||
|
Tooling
|
||||||
|
|
||||||
|
Usa sempre il venv: source venv/bin/activate.
|
||||||
|
|
||||||
|
Comando di test: pytest.
|
||||||
19
.opencode/skills/context7_documentation_retrivial/SKILL.md
Normal file
19
.opencode/skills/context7_documentation_retrivial/SKILL.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
Skill: Context7 Documentation Retrieval
|
||||||
|
|
||||||
|
Istruzioni per l'utilizzo di Context7 per eliminare allucinazioni su API e librerie.
|
||||||
|
|
||||||
|
Quando usare questa Skill
|
||||||
|
|
||||||
|
Prima di scrivere codice Python che utilizza librerie esterne (es. requests, pytest, supabase-py).
|
||||||
|
|
||||||
|
Quando si scrivono script Bash che utilizzano tool specifici (es. curl, jq).
|
||||||
|
|
||||||
|
Per verificare le ultime specifiche del Model Context Protocol (MCP).
|
||||||
|
|
||||||
|
Metodologia
|
||||||
|
|
||||||
|
Usa context7.search inserendo la libreria e la versione desiderata.
|
||||||
|
|
||||||
|
Integra i risultati nel contesto prima di generare il codice.
|
||||||
|
|
||||||
|
Se il codice generato fallisce i test, usa context7 per verificare se l'API utilizzata è deprecata.
|
||||||
424
.opencode/skills/examples/modal-implementation.md
Normal file
424
.opencode/skills/examples/modal-implementation.md
Normal file
@@ -0,0 +1,424 @@
|
|||||||
|
# Modal Implementation Example: Transaction Modal
|
||||||
|
|
||||||
|
Реальный пример из Family Budget: модальное окно для создания транзакции.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
- **Template**: `frontend/web/templates/components/modal_transaction.html`
|
||||||
|
- **JavaScript**: `frontend/web/static/js/budget/transactionForm.js`
|
||||||
|
- **Usage**: `frontend/web/templates/index.html`
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ index.html (parent template) │
|
||||||
|
│ │
|
||||||
|
│ {% from "components/modal_transaction.html" import │
|
||||||
|
│ transaction_modal %} │
|
||||||
|
│ │
|
||||||
|
│ {{ transaction_modal(modal_id='modal_add_transaction') }}│
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ modal_transaction.html (Jinja2 macro) │
|
||||||
|
│ │
|
||||||
|
│ <dialog id="{{ modal_id }}" class="modal"> │
|
||||||
|
│ <div class="modal-box"> │
|
||||||
|
│ <form id="form_{{ modal_id }}"> │
|
||||||
|
│ <!-- Form fields --> │
|
||||||
|
│ </form> │
|
||||||
|
│ </div> │
|
||||||
|
│ </dialog> │
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ transactionForm.js (CRUD logic) │
|
||||||
|
│ │
|
||||||
|
│ - saveTransaction() - POST /api/v1/facts │
|
||||||
|
│ - updateTransaction() - PUT /api/v1/facts/{id} │
|
||||||
|
│ - deleteTransaction() - DELETE /api/v1/facts/{id} │
|
||||||
|
│ - Offline sync via IndexedDB │
|
||||||
|
│ - WebSocket broadcast refresh │
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
### 1. Jinja2 Macro (modal_transaction.html)
|
||||||
|
|
||||||
|
```jinja2
|
||||||
|
{% macro transaction_modal(modal_id='modal_add_transaction') %}
|
||||||
|
<dialog id="{{ modal_id }}" class="modal">
|
||||||
|
<div class="modal-box w-full max-w-2xl p-4 max-h-[90vh] overflow-y-auto my-auto">
|
||||||
|
<h3 class="font-bold text-lg mb-3">➕ Добавить факт</h3>
|
||||||
|
|
||||||
|
<form id="form_{{ modal_id }}" class="space-y-2">
|
||||||
|
<!-- Дата -->
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label py-1">
|
||||||
|
<span class="label-text">Дата *</span>
|
||||||
|
</label>
|
||||||
|
<!-- Quick date buttons -->
|
||||||
|
<div class="flex gap-1 mb-1">
|
||||||
|
<button type="button" class="btn btn-xs btn-outline flex-1"
|
||||||
|
onclick="setTransactionDate(0)">Сегодня</button>
|
||||||
|
<button type="button" class="btn btn-xs btn-outline flex-1"
|
||||||
|
onclick="setTransactionDate(-1)">Вчера</button>
|
||||||
|
<button type="button" class="btn btn-xs btn-outline flex-1"
|
||||||
|
onclick="setTransactionDate(-2)">Позавчера</button>
|
||||||
|
</div>
|
||||||
|
<input type="text" name="fact_date" required
|
||||||
|
class="input input-bordered w-full transaction-date-input"
|
||||||
|
placeholder="ДД.ММ.ГГГГ" maxlength="10" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Счет (Financial Center) -->
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label py-1">
|
||||||
|
<span class="label-text">Счет *</span>
|
||||||
|
</label>
|
||||||
|
<select name="financial_center_id" required class="select select-bordered">
|
||||||
|
<option value="">-- Выберите счет --</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Тип операции (Radio buttons as DaisyUI buttons) -->
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label py-1">
|
||||||
|
<span class="label-text font-semibold">Тип операции *</span>
|
||||||
|
</label>
|
||||||
|
<div class="grid grid-cols-2 gap-2">
|
||||||
|
<label class="btn btn-sm btn-outline btn-error transaction-type-btn btn-active"
|
||||||
|
data-type="expense">
|
||||||
|
<input type="radio" name="record_type" value="expense" class="hidden" checked />
|
||||||
|
Расход
|
||||||
|
</label>
|
||||||
|
<label class="btn btn-sm btn-outline btn-success transaction-type-btn"
|
||||||
|
data-type="income">
|
||||||
|
<input type="radio" name="record_type" value="income" class="hidden" />
|
||||||
|
Доход
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Категория (Article) - filtered by Financial Center -->
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label py-1">
|
||||||
|
<span class="label-text">Категория *</span>
|
||||||
|
</label>
|
||||||
|
<select name="article_id" required class="select select-bordered">
|
||||||
|
<option value="" disabled hidden>-- Выберите категорию --</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Сумма -->
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label py-1">
|
||||||
|
<span class="label-text">Сумма *</span>
|
||||||
|
</label>
|
||||||
|
<input type="number" name="amount" step="1" min="1" required
|
||||||
|
class="input input-bordered" placeholder="0" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Описание -->
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label py-1">
|
||||||
|
<span class="label-text">Описание</span>
|
||||||
|
</label>
|
||||||
|
<textarea name="description" class="textarea textarea-bordered"
|
||||||
|
placeholder="Комментарий" rows="1"></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Modal Actions -->
|
||||||
|
<div class="modal-action mt-3">
|
||||||
|
<button type="button" onclick="{{ modal_id }}.close()" class="btn btn-sm btn-ghost">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
Отмена
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Unified save button (green online, orange offline) -->
|
||||||
|
<button type="button" class="btn btn-sm save-btn"
|
||||||
|
data-form-id="form_{{ modal_id }}"
|
||||||
|
data-modal-id="{{ modal_id }}"
|
||||||
|
onclick="saveTransaction(this)"
|
||||||
|
title="Сохранить">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
|
||||||
|
</svg>
|
||||||
|
Сохранить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Click backdrop to close -->
|
||||||
|
<form method="dialog" class="modal-backdrop">
|
||||||
|
<button>close</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
{% endmacro %}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. JavaScript Logic (transactionForm.js)
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* Save transaction (CREATE or UPDATE)
|
||||||
|
* Supports online/offline modes
|
||||||
|
*/
|
||||||
|
async function saveTransaction(button) {
|
||||||
|
const formId = button.dataset.formId;
|
||||||
|
const modalId = button.dataset.modalId;
|
||||||
|
const form = document.getElementById(formId);
|
||||||
|
const modal = document.getElementById(modalId);
|
||||||
|
|
||||||
|
// Validate form
|
||||||
|
if (!form.checkValidity()) {
|
||||||
|
form.reportValidity();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get form data
|
||||||
|
const formData = new FormData(form);
|
||||||
|
const data = Object.fromEntries(formData.entries());
|
||||||
|
|
||||||
|
// Convert types
|
||||||
|
data.amount = parseFloat(data.amount);
|
||||||
|
data.financial_center_id = parseInt(data.financial_center_id);
|
||||||
|
data.article_id = parseInt(data.article_id);
|
||||||
|
if (data.cost_center_id) {
|
||||||
|
data.cost_center_id = parseInt(data.cost_center_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check if online or offline
|
||||||
|
if (navigator.onLine) {
|
||||||
|
// Online: POST to API
|
||||||
|
const response = await fetch('/api/v1/facts', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json();
|
||||||
|
throw new Error(error.detail || 'Failed to save transaction');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
console.log('Transaction saved:', result.id);
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
modal.close();
|
||||||
|
|
||||||
|
// Refresh data via HTMX
|
||||||
|
htmx.trigger('#recent-transactions', 'refresh');
|
||||||
|
htmx.trigger('#quick-stats', 'refresh');
|
||||||
|
|
||||||
|
// Show success toast
|
||||||
|
showToast('Транзакция сохранена', 'success');
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Offline: Save to IndexedDB
|
||||||
|
await window.offlineSync.queueTransaction(data);
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
modal.close();
|
||||||
|
|
||||||
|
// Show offline toast
|
||||||
|
showToast('Сохранено offline (синхронизируется при подключении)', 'warning');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Save transaction error:', error);
|
||||||
|
showToast(error.message || 'Ошибка сохранения', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open modal for creating new transaction
|
||||||
|
*/
|
||||||
|
function openAddTransactionModal() {
|
||||||
|
const modal = document.getElementById('modal_add_transaction');
|
||||||
|
const form = document.getElementById('form_modal_add_transaction');
|
||||||
|
|
||||||
|
// Reset form
|
||||||
|
form.reset();
|
||||||
|
|
||||||
|
// Set default date (today)
|
||||||
|
setTransactionDate(0);
|
||||||
|
|
||||||
|
// Set default type (expense)
|
||||||
|
document.querySelector('input[name="record_type"][value="expense"]').checked = true;
|
||||||
|
document.querySelectorAll('.transaction-type-btn').forEach(btn => {
|
||||||
|
btn.classList.remove('btn-active');
|
||||||
|
});
|
||||||
|
document.querySelector('.transaction-type-btn[data-type="expense"]').classList.add('btn-active');
|
||||||
|
|
||||||
|
// Load Financial Centers and Articles
|
||||||
|
loadFormOptions();
|
||||||
|
|
||||||
|
// Open modal
|
||||||
|
modal.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set transaction date
|
||||||
|
* @param {number} daysOffset - Days offset from today (0=today, -1=yesterday, etc.)
|
||||||
|
*/
|
||||||
|
function setTransactionDate(daysOffset) {
|
||||||
|
const date = new Date();
|
||||||
|
date.setDate(date.getDate() + daysOffset);
|
||||||
|
|
||||||
|
const dateStr = date.toLocaleDateString('ru-RU', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: '2-digit',
|
||||||
|
year: 'numeric'
|
||||||
|
});
|
||||||
|
|
||||||
|
const input = document.querySelector('.transaction-date-input');
|
||||||
|
if (input) {
|
||||||
|
input.value = dateStr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load Financial Centers and Articles for form
|
||||||
|
*/
|
||||||
|
async function loadFormOptions() {
|
||||||
|
try {
|
||||||
|
// Load Financial Centers
|
||||||
|
const fcResponse = await fetch('/api/v1/financial-centers');
|
||||||
|
const financialCenters = await fcResponse.json();
|
||||||
|
|
||||||
|
const fcSelect = document.querySelector('select[name="financial_center_id"]');
|
||||||
|
fcSelect.innerHTML = '<option value="">-- Выберите счет --</option>';
|
||||||
|
financialCenters.forEach(fc => {
|
||||||
|
fcSelect.innerHTML += `<option value="${fc.id}">${fc.name}</option>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Load Articles (filtered by Financial Center after selection)
|
||||||
|
const articlesResponse = await fetch('/api/v1/articles');
|
||||||
|
const articles = await articlesResponse.json();
|
||||||
|
|
||||||
|
const articleSelect = document.querySelector('select[name="article_id"]');
|
||||||
|
articleSelect.innerHTML = '<option value="">-- Выберите категорию --</option>';
|
||||||
|
articles.forEach(article => {
|
||||||
|
articleSelect.innerHTML += `<option value="${article.id}">${article.name}</option>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Load form options error:', error);
|
||||||
|
showToast('Ошибка загрузки справочников', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Usage in Template
|
||||||
|
|
||||||
|
```jinja2
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% from "components/modal_transaction.html" import transaction_modal %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<!-- Page content -->
|
||||||
|
<div class="space-y-6">
|
||||||
|
<!-- Quick actions -->
|
||||||
|
<button onclick="openAddTransactionModal()" class="btn btn-success">
|
||||||
|
➕ Добавить факт
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Recent transactions -->
|
||||||
|
<div id="recent-transactions" hx-get="/api/v1/facts/recent" hx-trigger="load">
|
||||||
|
<!-- Loaded via HTMX -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Modal (outside content div) -->
|
||||||
|
{{ transaction_modal(modal_id='modal_add_transaction') }}
|
||||||
|
{% endblock %}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
### 1. DaisyUI Modal
|
||||||
|
|
||||||
|
```html
|
||||||
|
<dialog id="modal_id" class="modal">
|
||||||
|
<div class="modal-box">...</div>
|
||||||
|
<form method="dialog" class="modal-backdrop">
|
||||||
|
<button>close</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
```
|
||||||
|
|
||||||
|
- Native `<dialog>` element (HTML5)
|
||||||
|
- DaisyUI classes: `modal`, `modal-box`, `modal-backdrop`
|
||||||
|
- JavaScript API: `modal.showModal()`, `modal.close()`
|
||||||
|
|
||||||
|
### 2. Form Validation
|
||||||
|
|
||||||
|
- HTML5 validation: `required`, `min`, `maxlength`
|
||||||
|
- JavaScript: `form.checkValidity()`, `form.reportValidity()`
|
||||||
|
- Custom validation in `saveTransaction()`
|
||||||
|
|
||||||
|
### 3. Offline Support
|
||||||
|
|
||||||
|
- Check `navigator.onLine`
|
||||||
|
- Save to IndexedDB when offline
|
||||||
|
- Sync queue processed when back online
|
||||||
|
- Visual feedback (orange button when offline)
|
||||||
|
|
||||||
|
### 4. HTMX Integration
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Refresh HTMX content after save
|
||||||
|
htmx.trigger('#recent-transactions', 'refresh');
|
||||||
|
htmx.trigger('#quick-stats', 'refresh');
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Radio Buttons as Buttons
|
||||||
|
|
||||||
|
```html
|
||||||
|
<label class="btn btn-outline btn-error transaction-type-btn">
|
||||||
|
<input type="radio" name="record_type" value="expense" class="hidden" />
|
||||||
|
Расход
|
||||||
|
</label>
|
||||||
|
```
|
||||||
|
|
||||||
|
- Styled as DaisyUI buttons
|
||||||
|
- Hidden radio input
|
||||||
|
- Toggle `btn-active` class on click
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
- **Modal open**: <100ms (minimal JavaScript)
|
||||||
|
- **Form load**: ~200ms (2 API calls in parallel)
|
||||||
|
- **Save**: ~150ms (POST + HTMX refresh)
|
||||||
|
- **Offline save**: ~50ms (IndexedDB write)
|
||||||
|
|
||||||
|
## Accessibility
|
||||||
|
|
||||||
|
- ✅ Keyboard navigation (Tab, Enter, Esc)
|
||||||
|
- ✅ ARIA labels (implicit from `<label>` elements)
|
||||||
|
- ✅ Focus management (auto-focus first input when opened)
|
||||||
|
- ✅ Screen reader compatible (DaisyUI semantic HTML)
|
||||||
|
|
||||||
|
## Browser Support
|
||||||
|
|
||||||
|
- ✅ Chrome/Edge (full support)
|
||||||
|
- ✅ Firefox (full support)
|
||||||
|
- ✅ Safari (full support, including iOS)
|
||||||
|
- ✅ Mobile browsers (responsive design)
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- DaisyUI Modal: https://daisyui.com/components/modal/
|
||||||
|
- HTMX: https://htmx.org/
|
||||||
|
- HTML Dialog Element: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog
|
||||||
301
.opencode/skills/examples/ws-integration.md
Normal file
301
.opencode/skills/examples/ws-integration.md
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
# WebSocket Integration Example
|
||||||
|
|
||||||
|
Реальный пример из Family Budget: интеграция WebSocket для real-time обновлений.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
- **WebSocket Client**: `frontend/web/static/js/budget/budgetWSClient.js`
|
||||||
|
- **Backend Manager**: `backend/app/api/v1/endpoints/budget_sse.py`
|
||||||
|
- **Usage**: `frontend/web/templates/base.html`
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ Frontend: budgetWSClient.js │
|
||||||
|
│ │
|
||||||
|
│ new BudgetWSClient() → WebSocket("/api/v1/budget/ws") │
|
||||||
|
│ ↓ │
|
||||||
|
│ Event handlers: │
|
||||||
|
│ - budget_fact_created │
|
||||||
|
│ - budget_fact_updated │
|
||||||
|
│ - budget_fact_deleted │
|
||||||
|
│ - article_updated │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
↓ (WebSocket)
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ Backend: BudgetConnectionManager (in-memory) │
|
||||||
|
│ │
|
||||||
|
│ - Active connections: Map<connection_id, WebSocket> │
|
||||||
|
│ - Broadcast events to all connected clients │
|
||||||
|
│ - WORKERS=1 constraint (no Redis Pub/Sub) │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
↑ (Broadcast)
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ API Endpoints: /api/v1/facts │
|
||||||
|
│ │
|
||||||
|
│ POST /facts → ws_manager.broadcast("budget_fact_created", data) │
|
||||||
|
│ PUT /facts/{id} → ws_manager.broadcast("budget_fact_updated", data) │
|
||||||
|
│ DELETE /facts/{id} → ws_manager.broadcast("budget_fact_deleted", data) │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Frontend Implementation
|
||||||
|
|
||||||
|
### 1. Initialize WebSocket Client
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// In base.html (global scope)
|
||||||
|
<script type="module">
|
||||||
|
import { BudgetWSClient } from '/static/js/budget/budgetWSClient.js';
|
||||||
|
window.budgetWS = new BudgetWSClient();
|
||||||
|
|
||||||
|
// Register event handlers
|
||||||
|
budgetWS.on('budget_fact_created', (data) => {
|
||||||
|
console.log('New fact created:', data);
|
||||||
|
// Refresh HTMX content
|
||||||
|
htmx.trigger('#recent-transactions', 'refresh');
|
||||||
|
htmx.trigger('#quick-stats', 'refresh');
|
||||||
|
});
|
||||||
|
|
||||||
|
budgetWS.on('budget_fact_updated', (data) => {
|
||||||
|
console.log('Fact updated:', data);
|
||||||
|
htmx.trigger('#recent-transactions', 'refresh');
|
||||||
|
});
|
||||||
|
|
||||||
|
budgetWS.on('budget_fact_deleted', (data) => {
|
||||||
|
console.log('Fact deleted:', data.id);
|
||||||
|
htmx.trigger('#recent-transactions', 'refresh');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
budgetWS.connect();
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. WebSocket Client (Simplified)
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
export class BudgetWSClient {
|
||||||
|
constructor() {
|
||||||
|
this.ws = null;
|
||||||
|
this.isConnected = false;
|
||||||
|
this.handlers = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
connect() {
|
||||||
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
|
const wsUrl = `${protocol}//${window.location.host}/api/v1/budget/ws`;
|
||||||
|
|
||||||
|
this.ws = new WebSocket(wsUrl);
|
||||||
|
|
||||||
|
this.ws.onopen = () => {
|
||||||
|
console.log('[BudgetWS] Connected');
|
||||||
|
this.isConnected = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onmessage = (event) => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
const { event: eventType, data } = message;
|
||||||
|
|
||||||
|
// Trigger registered handlers
|
||||||
|
if (this.handlers[eventType]) {
|
||||||
|
this.handlers[eventType].forEach(handler => handler(data));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onclose = () => {
|
||||||
|
console.log('[BudgetWS] Disconnected');
|
||||||
|
this.isConnected = false;
|
||||||
|
// Reconnect after 3 seconds
|
||||||
|
setTimeout(() => this.connect(), 3000);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onerror = (error) => {
|
||||||
|
console.error('[BudgetWS] Error:', error);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
on(event, handler) {
|
||||||
|
if (!this.handlers[event]) {
|
||||||
|
this.handlers[event] = [];
|
||||||
|
}
|
||||||
|
this.handlers[event].push(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
if (this.ws) {
|
||||||
|
this.ws.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Backend Implementation
|
||||||
|
|
||||||
|
### 1. WebSocket Manager
|
||||||
|
|
||||||
|
```python
|
||||||
|
# backend/app/api/v1/endpoints/budget_sse.py
|
||||||
|
|
||||||
|
from fastapi import WebSocket, WebSocketDisconnect
|
||||||
|
from typing import Dict
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class BudgetConnectionManager:
|
||||||
|
"""
|
||||||
|
In-memory WebSocket connection manager
|
||||||
|
|
||||||
|
CRITICAL: Works only with WORKERS=1
|
||||||
|
Multiple workers = separate managers = lost events
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.active_connections: Dict[str, WebSocket] = {}
|
||||||
|
|
||||||
|
async def connect(self, websocket: WebSocket, connection_id: str):
|
||||||
|
await websocket.accept()
|
||||||
|
self.active_connections[connection_id] = websocket
|
||||||
|
logger.info(f"WebSocket connected: {connection_id}")
|
||||||
|
|
||||||
|
def disconnect(self, connection_id: str):
|
||||||
|
if connection_id in self.active_connections:
|
||||||
|
del self.active_connections[connection_id]
|
||||||
|
logger.info(f"WebSocket disconnected: {connection_id}")
|
||||||
|
|
||||||
|
async def broadcast(self, event: str, data: dict):
|
||||||
|
"""Broadcast event to all connected clients"""
|
||||||
|
message = {"event": event, "data": data}
|
||||||
|
|
||||||
|
disconnected = []
|
||||||
|
for conn_id, websocket in self.active_connections.items():
|
||||||
|
try:
|
||||||
|
await websocket.send_json(message)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Broadcast error to {conn_id}: {e}")
|
||||||
|
disconnected.append(conn_id)
|
||||||
|
|
||||||
|
# Remove disconnected clients
|
||||||
|
for conn_id in disconnected:
|
||||||
|
self.disconnect(conn_id)
|
||||||
|
|
||||||
|
# Global instance
|
||||||
|
ws_manager = BudgetConnectionManager()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. WebSocket Endpoint
|
||||||
|
|
||||||
|
```python
|
||||||
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.websocket("/ws")
|
||||||
|
async def websocket_endpoint(websocket: WebSocket):
|
||||||
|
connection_id = str(uuid.uuid4())
|
||||||
|
|
||||||
|
await ws_manager.connect(websocket, connection_id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
# Keep connection alive (receive pings)
|
||||||
|
data = await websocket.receive_text()
|
||||||
|
# Optional: handle client messages
|
||||||
|
except WebSocketDisconnect:
|
||||||
|
ws_manager.disconnect(connection_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Broadcast from API Endpoints
|
||||||
|
|
||||||
|
```python
|
||||||
|
# backend/app/api/v1/endpoints/facts.py
|
||||||
|
|
||||||
|
@router.post("/", response_model=FactResponse)
|
||||||
|
async def create_fact(
|
||||||
|
fact_data: FactCreate,
|
||||||
|
session: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
# Create fact
|
||||||
|
fact = await fact_service.create_fact(session, fact_data, current_user)
|
||||||
|
|
||||||
|
# Broadcast WebSocket event
|
||||||
|
await ws_manager.broadcast(
|
||||||
|
"budget_fact_created",
|
||||||
|
{
|
||||||
|
"id": fact.id,
|
||||||
|
"amount": fact.amount,
|
||||||
|
"article_id": fact.article_id,
|
||||||
|
"financial_center_id": fact.financial_center_id,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return fact
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
### 1. Auto-Reconnect
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
this.ws.onclose = () => {
|
||||||
|
setTimeout(() => this.connect(), 3000); // Reconnect after 3 sec
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Event-Driven Architecture
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Register handler
|
||||||
|
budgetWS.on('budget_fact_created', (data) => {
|
||||||
|
// Handle event
|
||||||
|
});
|
||||||
|
|
||||||
|
// Broadcast from backend
|
||||||
|
await ws_manager.broadcast("budget_fact_created", data);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. HTMX Integration
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Refresh HTMX content on WebSocket event
|
||||||
|
htmx.trigger('#recent-transactions', 'refresh');
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Single Worker Constraint
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# docker-compose.yml
|
||||||
|
services:
|
||||||
|
backend:
|
||||||
|
command: uvicorn app.main:app --workers 1 # CRITICAL!
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why WORKERS=1?**
|
||||||
|
- `BudgetConnectionManager` is in-memory
|
||||||
|
- Each worker has separate instance
|
||||||
|
- Events don't propagate between workers
|
||||||
|
- User A (worker 1) creates fact → only worker 1 clients receive event
|
||||||
|
- User B (worker 2) doesn't see update
|
||||||
|
|
||||||
|
**Future: Redis Pub/Sub**
|
||||||
|
- Use Redis for event broadcasting
|
||||||
|
- Workers subscribe to Redis channel
|
||||||
|
- Events propagate across all workers
|
||||||
|
- Can scale to multiple workers
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
- **Connection time**: ~100ms
|
||||||
|
- **Event latency**: <50ms (same worker)
|
||||||
|
- **Reconnect time**: 3 seconds
|
||||||
|
- **Memory**: ~5KB per connection
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- **WebSocket API**: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
|
||||||
|
- **FastAPI WebSocket**: https://fastapi.tiangolo.com/advanced/websockets/
|
||||||
|
- **Real implementation**: `frontend/web/static/js/budget/budgetWSClient.js`
|
||||||
291
.opencode/skills/felvieira-ui-ux-design/SKILL.md
Normal file
291
.opencode/skills/felvieira-ui-ux-design/SKILL.md
Normal file
@@ -0,0 +1,291 @@
|
|||||||
|
---
|
||||||
|
name: ui-ux-design
|
||||||
|
description: |
|
||||||
|
Skill do Designer UI/UX para definição de interfaces e experiência do usuário. Use quando precisar criar
|
||||||
|
wireframes, design system tokens, componentes de UI, fluxos de navegação, acessibilidade, ou qualquer
|
||||||
|
decisão de interface. Trigger em: "design", "UI", "UX", "interface", "wireframe", "componente visual",
|
||||||
|
"layout", "responsivo", "mobile first", "acessibilidade", "design system", "protótipo", "Figma".
|
||||||
|
---
|
||||||
|
|
||||||
|
# UI/UX Designer - Interface e Usabilidade
|
||||||
|
|
||||||
|
O Designer é responsável por traduzir user stories em interfaces utilizáveis, acessíveis e bonitas.
|
||||||
|
|
||||||
|
## Governanca Global
|
||||||
|
|
||||||
|
Esta skill segue `GLOBAL.md`, `policies/execution.md`, `policies/handoffs.md`, `policies/token-efficiency.md`, `policies/stack-flexibility.md` e `policies/evals.md`.
|
||||||
|
|
||||||
|
Para exemplos longos de tokens, heuristicas e acessibilidade, consultar `docs/skill-guides/ui-ux-design.md` apenas quando necessario.
|
||||||
|
|
||||||
|
Para uso de MCPs de bibliotecas visuais como referencia ou aceleracao, consultar `docs/skill-guides/ui-component-mcps.md`.
|
||||||
|
|
||||||
|
## Quando Usar
|
||||||
|
|
||||||
|
- definir interface, fluxo e comportamento responsivo
|
||||||
|
- transformar spec em estrutura de tela e decisao de usabilidade
|
||||||
|
|
||||||
|
## Quando Nao Usar
|
||||||
|
|
||||||
|
- para decidir regras de negocio ou contrato de API sozinho
|
||||||
|
- para substituir implementacao frontend
|
||||||
|
|
||||||
|
## Entradas Esperadas
|
||||||
|
|
||||||
|
- spec do PO
|
||||||
|
- restricoes de plataforma e acessibilidade
|
||||||
|
- contexto de usuarios e fluxos principais
|
||||||
|
- dossie de Design Intelligence (skill 29), quando disponivel: concorrentes analisados, tendencias visuais, moodboards, paleta e tipografia sugeridas, direcao estrategica (copiar/evitar/diferenciar)
|
||||||
|
|
||||||
|
## Saidas Esperadas
|
||||||
|
|
||||||
|
- wireframe, fluxo ou direcao de interface
|
||||||
|
- regras de responsividade e acessibilidade
|
||||||
|
- handoff claro para Frontend e, se necessario, Backend
|
||||||
|
|
||||||
|
## Responsabilidades
|
||||||
|
|
||||||
|
1. Definir arquitetura de informação e fluxos de navegação
|
||||||
|
2. Criar wireframes e protótipos
|
||||||
|
3. Manter design system consistente
|
||||||
|
4. Garantir acessibilidade (WCAG 2.1 AA mínimo)
|
||||||
|
5. Definir breakpoints e comportamento responsivo
|
||||||
|
6. Validar usabilidade com heurísticas de Nielsen
|
||||||
|
|
||||||
|
## Bibliotecas com MCP
|
||||||
|
|
||||||
|
Quando a tarefa se beneficiar de bibliotecas prontas de componentes ou motion, esta skill pode consultar ou configurar MCPs como `Magic UI MCP` e `React Bits MCP`, desde que:
|
||||||
|
|
||||||
|
- o projeto seja compativel com a stack exigida
|
||||||
|
- a integracao nao conflite com o design system existente
|
||||||
|
- o componente seja adaptado ao contexto visual real do app
|
||||||
|
|
||||||
|
Se o projeto ja tiver componentes, branding ou linguagem visual estabelecidos, o MCP serve como referencia ou acelerador, nunca como desculpa para destoar do produto.
|
||||||
|
|
||||||
|
## Design System - Tokens Base
|
||||||
|
|
||||||
|
Todo projeto começa com a definição destes tokens:
|
||||||
|
|
||||||
|
**src/lib/design-tokens.ts**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const tokens = {
|
||||||
|
colors: {
|
||||||
|
primary: {
|
||||||
|
50: '#eff6ff',
|
||||||
|
100: '#dbeafe',
|
||||||
|
200: '#bfdbfe',
|
||||||
|
300: '#93c5fd',
|
||||||
|
400: '#60a5fa',
|
||||||
|
500: '#3b82f6',
|
||||||
|
600: '#2563eb',
|
||||||
|
700: '#1d4ed8',
|
||||||
|
800: '#1e40af',
|
||||||
|
900: '#1e3a8a',
|
||||||
|
},
|
||||||
|
success: '#22c55e',
|
||||||
|
warning: '#f59e0b',
|
||||||
|
error: '#ef4444',
|
||||||
|
info: '#3b82f6',
|
||||||
|
gray: {
|
||||||
|
50: '#f9fafb',
|
||||||
|
100: '#f3f4f6',
|
||||||
|
200: '#e5e7eb',
|
||||||
|
300: '#d1d5db',
|
||||||
|
400: '#9ca3af',
|
||||||
|
500: '#6b7280',
|
||||||
|
600: '#4b5563',
|
||||||
|
700: '#374151',
|
||||||
|
800: '#1f2937',
|
||||||
|
900: '#111827',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
spacing: {
|
||||||
|
xs: '0.25rem',
|
||||||
|
sm: '0.5rem',
|
||||||
|
md: '1rem',
|
||||||
|
lg: '1.5rem',
|
||||||
|
xl: '2rem',
|
||||||
|
'2xl': '3rem',
|
||||||
|
'3xl': '4rem',
|
||||||
|
},
|
||||||
|
typography: {
|
||||||
|
fontFamily: {
|
||||||
|
sans: "'Inter', -apple-system, BlinkMacSystemFont, sans-serif",
|
||||||
|
mono: "'JetBrains Mono', 'Fira Code', monospace",
|
||||||
|
},
|
||||||
|
fontSize: {
|
||||||
|
xs: ['0.75rem', { lineHeight: '1rem' }],
|
||||||
|
sm: ['0.875rem', { lineHeight: '1.25rem' }],
|
||||||
|
base: ['1rem', { lineHeight: '1.5rem' }],
|
||||||
|
lg: ['1.125rem', { lineHeight: '1.75rem' }],
|
||||||
|
xl: ['1.25rem', { lineHeight: '1.75rem' }],
|
||||||
|
'2xl': ['1.5rem', { lineHeight: '2rem' }],
|
||||||
|
'3xl': ['1.875rem', { lineHeight: '2.25rem' }],
|
||||||
|
'4xl': ['2.25rem', { lineHeight: '2.5rem' }],
|
||||||
|
},
|
||||||
|
fontWeight: {
|
||||||
|
normal: '400',
|
||||||
|
medium: '500',
|
||||||
|
semibold: '600',
|
||||||
|
bold: '700',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
borderRadius: {
|
||||||
|
none: '0',
|
||||||
|
sm: '0.25rem',
|
||||||
|
md: '0.375rem',
|
||||||
|
lg: '0.5rem',
|
||||||
|
xl: '0.75rem',
|
||||||
|
'2xl': '1rem',
|
||||||
|
full: '9999px',
|
||||||
|
},
|
||||||
|
shadows: {
|
||||||
|
sm: '0 1px 2px 0 rgb(0 0 0 / 0.05)',
|
||||||
|
md: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
|
||||||
|
lg: '0 10px 15px -3px rgb(0 0 0 / 0.1)',
|
||||||
|
xl: '0 20px 25px -5px rgb(0 0 0 / 0.1)',
|
||||||
|
},
|
||||||
|
breakpoints: {
|
||||||
|
sm: '640px',
|
||||||
|
md: '768px',
|
||||||
|
lg: '1024px',
|
||||||
|
xl: '1280px',
|
||||||
|
'2xl': '1536px',
|
||||||
|
},
|
||||||
|
transitions: {
|
||||||
|
fast: '150ms ease',
|
||||||
|
normal: '250ms ease',
|
||||||
|
slow: '350ms ease',
|
||||||
|
},
|
||||||
|
zIndex: {
|
||||||
|
dropdown: 1000,
|
||||||
|
sticky: 1020,
|
||||||
|
fixed: 1030,
|
||||||
|
modal: 1040,
|
||||||
|
popover: 1050,
|
||||||
|
tooltip: 1060,
|
||||||
|
toast: 1070,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Breakpoints e Responsividade
|
||||||
|
|
||||||
|
Abordagem **Mobile First** obrigatória:
|
||||||
|
|
||||||
|
```
|
||||||
|
Mobile: 0 - 639px → Layout single column, touch targets 44px mín
|
||||||
|
Tablet: 640 - 1023px → Layout adaptado, sidebar colapsável
|
||||||
|
Desktop: 1024px+ → Layout completo, múltiplas colunas
|
||||||
|
```
|
||||||
|
|
||||||
|
Regras de responsividade:
|
||||||
|
- Imagens: usar `object-fit: cover` + `aspect-ratio` definido
|
||||||
|
- Tabelas: viram cards em mobile (padrão stacked)
|
||||||
|
- Navegação: hamburger em mobile, sidebar em desktop
|
||||||
|
- Formulários: inputs full-width em mobile, grid em desktop
|
||||||
|
- Touch targets: mínimo 44x44px em mobile
|
||||||
|
- Font-size mínimo: 16px em inputs (evita zoom no iOS)
|
||||||
|
|
||||||
|
## Componentes - Padrão de Especificação
|
||||||
|
|
||||||
|
Cada componente deve ter:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Componente: [Nome]
|
||||||
|
|
||||||
|
### Variantes
|
||||||
|
- Default / Primary / Secondary / Ghost / Destructive
|
||||||
|
|
||||||
|
### Estados
|
||||||
|
- Default / Hover / Focus / Active / Disabled / Loading / Error
|
||||||
|
|
||||||
|
### Props
|
||||||
|
| Prop | Tipo | Default | Descrição |
|
||||||
|
|------|------|---------|-----------|
|
||||||
|
| variant | string | 'default' | Estilo visual |
|
||||||
|
| size | 'sm' \| 'md' \| 'lg' | 'md' | Tamanho |
|
||||||
|
| disabled | boolean | false | Desabilita interação |
|
||||||
|
| loading | boolean | false | Mostra skeleton/spinner |
|
||||||
|
|
||||||
|
### Acessibilidade
|
||||||
|
- Role ARIA: [role]
|
||||||
|
- Keyboard: [teclas suportadas]
|
||||||
|
- Screen reader: [comportamento esperado]
|
||||||
|
|
||||||
|
### Skeleton
|
||||||
|
- Formato do skeleton que aparece durante loading
|
||||||
|
- Dimensões devem refletir o conteúdo final (evitar layout shift)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Skeleton Loading - Padrões
|
||||||
|
|
||||||
|
Skeleton é obrigatório em toda tela que faz fetch de dados:
|
||||||
|
|
||||||
|
```
|
||||||
|
Tipos de skeleton:
|
||||||
|
├── TextSkeleton → Linhas com largura variável (100%, 80%, 60%)
|
||||||
|
├── AvatarSkeleton → Círculo (sm: 32px, md: 40px, lg: 48px)
|
||||||
|
├── CardSkeleton → Retângulo com rounded corners
|
||||||
|
├── TableSkeleton → Grid de retângulos imitando rows
|
||||||
|
├── ImageSkeleton → Retângulo com aspect-ratio da imagem
|
||||||
|
└── FormSkeleton → Inputs placeholder com labels
|
||||||
|
```
|
||||||
|
|
||||||
|
Regras:
|
||||||
|
- Skeleton DEVE refletir o layout final (mesmas dimensões)
|
||||||
|
- Animação: pulse (não shimmer — mais leve)
|
||||||
|
- Cor: gray-200 com pulse para gray-300
|
||||||
|
- Nunca mostrar skeleton por mais de 3s — se demorar, mostrar mensagem
|
||||||
|
|
||||||
|
## Heurísticas de Nielsen - Checklist
|
||||||
|
|
||||||
|
Antes de aprovar qualquer interface, validar:
|
||||||
|
|
||||||
|
1. **Visibilidade do status** — Usuário sempre sabe o que tá acontecendo?
|
||||||
|
2. **Compatibilidade com o mundo real** — Linguagem do usuário, não jargão técnico?
|
||||||
|
3. **Controle e liberdade** — Tem "desfazer"? Tem "voltar"?
|
||||||
|
4. **Consistência e padrões** — Mesma ação = mesmo visual em toda app?
|
||||||
|
5. **Prevenção de erros** — Confirmação antes de ações destrutivas?
|
||||||
|
6. **Reconhecer ao invés de lembrar** — Info visível, não memorizada?
|
||||||
|
7. **Flexibilidade e eficiência** — Atalhos pra usuários avançados?
|
||||||
|
8. **Design minimalista** — Só info relevante na tela?
|
||||||
|
9. **Recuperação de erros** — Mensagens claras com ação sugerida?
|
||||||
|
10. **Ajuda e documentação** — Tooltips, onboarding?
|
||||||
|
|
||||||
|
## Evidencia de Conclusao
|
||||||
|
|
||||||
|
- fluxo principal definido
|
||||||
|
- estados de loading, erro e vazio considerados
|
||||||
|
- responsividade e acessibilidade especificadas
|
||||||
|
|
||||||
|
## Handoff para Frontend
|
||||||
|
|
||||||
|
Entregar:
|
||||||
|
1. Wireframes/mockups com estados (default, loading, error, empty, success)
|
||||||
|
2. Design tokens configurados
|
||||||
|
3. Especificação de cada componente novo
|
||||||
|
4. Fluxo de navegação completo
|
||||||
|
5. Comportamento responsivo definido por breakpoint
|
||||||
|
6. Skeleton patterns para cada tela
|
||||||
|
7. Micro-interações e animações especificadas
|
||||||
|
8. Acessibilidade: roles ARIA, tab order, screen reader labels
|
||||||
|
|
||||||
|
## Handoff para Backend
|
||||||
|
|
||||||
|
Comunicar:
|
||||||
|
1. Dados necessários por tela (quais campos, formatos)
|
||||||
|
2. Paginação: tipo (offset vs cursor), itens por página
|
||||||
|
3. Filtros e ordenação que a UI precisa
|
||||||
|
4. Estados de loading e como o skeleton se comporta
|
||||||
|
5. Feedback visual que depende de resposta da API (sucesso, erro)
|
||||||
|
|
||||||
|
## Código Limpo
|
||||||
|
|
||||||
|
Codigo deve priorizar clareza. Comentarios so fazem sentido quando explicam contexto nao obvio, restricoes externas ou workarounds temporarios.
|
||||||
|
|
||||||
|
## Integração com Pipeline
|
||||||
|
|
||||||
|
- **Orquestrador (skill 09):** Coordena quando esta skill é invocada e define a próxima etapa
|
||||||
|
- **Context Manager (skill 08):** Rastreia progresso das tasks dentro desta skill
|
||||||
|
- **Documentador (skill 10):** Documenta entregas desta skill durante o desenvolvimento
|
||||||
177
.opencode/skills/frontend-design-guidelines/SKILL.md
Normal file
177
.opencode/skills/frontend-design-guidelines/SKILL.md
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
---
|
||||||
|
name: frontend-design
|
||||||
|
model: reasoning
|
||||||
|
version: 1.1.0
|
||||||
|
description: >
|
||||||
|
Create distinctive, production-grade frontend interfaces that avoid generic "AI slop"
|
||||||
|
aesthetics. Focuses on creative direction and memorable design choices.
|
||||||
|
tags: [frontend, design, ui, web, aesthetics, creative]
|
||||||
|
related: [ui-design, web-design, theme-factory]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Frontend Design
|
||||||
|
|
||||||
|
Create memorable frontend interfaces that stand out from generic AI-generated aesthetics through bold creative choices.
|
||||||
|
|
||||||
|
> **See also:** `ui-design` for fundamentals (typography, color, spacing), `web-design` for CSS patterns.
|
||||||
|
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
### OpenClaw / Moltbot / Clawbot
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx clawhub@latest install frontend-design
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## WHAT This Skill Does
|
||||||
|
|
||||||
|
Guides creation of visually distinctive web interfaces by:
|
||||||
|
- Establishing a bold aesthetic direction before coding
|
||||||
|
- Making intentional typography, color, and spatial choices
|
||||||
|
- Implementing motion and micro-interactions that delight
|
||||||
|
- Avoiding the predictable patterns that mark AI-generated UIs
|
||||||
|
|
||||||
|
## WHEN To Use
|
||||||
|
|
||||||
|
- Building a new component, page, or web application
|
||||||
|
- Creating landing pages, marketing sites, or product UIs
|
||||||
|
- Redesigning interfaces to be more memorable
|
||||||
|
- Any frontend work where visual impact matters
|
||||||
|
|
||||||
|
## KEYWORDS
|
||||||
|
|
||||||
|
frontend design, web ui, ui design, landing page, creative ui, web aesthetics, typography, visual design, motion design, distinctive interface
|
||||||
|
|
||||||
|
## Design Thinking Process
|
||||||
|
|
||||||
|
Before writing code, commit to an aesthetic direction:
|
||||||
|
|
||||||
|
### 1. Understand Context
|
||||||
|
- **Purpose**: What problem does this interface solve?
|
||||||
|
- **Audience**: Who uses it and what do they expect?
|
||||||
|
- **Constraints**: Framework, performance, accessibility requirements
|
||||||
|
|
||||||
|
### 2. Choose a Bold Direction
|
||||||
|
|
||||||
|
Pick an extreme aesthetic — mediocrity is forgettable:
|
||||||
|
|
||||||
|
| Direction | Characteristics |
|
||||||
|
|-----------|-----------------|
|
||||||
|
| **Brutally Minimal** | Stark, essential, nothing extra |
|
||||||
|
| **Maximalist Chaos** | Dense, layered, overwhelming intentionally |
|
||||||
|
| **Retro-Futuristic** | Blends vintage aesthetics with modern tech |
|
||||||
|
| **Organic/Natural** | Soft, flowing, nature-inspired |
|
||||||
|
| **Luxury/Refined** | Premium materials, subtle elegance |
|
||||||
|
| **Playful/Toy-like** | Fun, approachable, bright |
|
||||||
|
| **Editorial/Magazine** | Type-forward, grid-based |
|
||||||
|
| **Brutalist/Raw** | Exposed structure, anti-design |
|
||||||
|
| **Art Deco/Geometric** | Bold shapes, symmetry, ornament |
|
||||||
|
| **Industrial/Utilitarian** | Function-forward, robust |
|
||||||
|
|
||||||
|
### 3. Identify the Memorable Element
|
||||||
|
|
||||||
|
What single thing will someone remember about this interface? Commit to it.
|
||||||
|
|
||||||
|
## Aesthetic Guidelines
|
||||||
|
|
||||||
|
### Typography
|
||||||
|
|
||||||
|
**NEVER** use generic fonts:
|
||||||
|
- Arial, Helvetica, system-ui
|
||||||
|
- Inter, Roboto (unless highly intentional)
|
||||||
|
|
||||||
|
**DO** choose distinctive fonts:
|
||||||
|
- Pair a characterful display font with a refined body font
|
||||||
|
- Explore: Space Grotesk, Clash Display, Cabinet Grotesk, Satoshi, General Sans, Instrument Serif, Fraunces, Newsreader
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* Example pairing */
|
||||||
|
--font-display: 'Clash Display', sans-serif;
|
||||||
|
--font-body: 'Satoshi', sans-serif;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Color & Theme
|
||||||
|
|
||||||
|
- **Commit** to a cohesive palette — don't hedge with safe choices
|
||||||
|
- **Dominant + accent** outperforms evenly-distributed colors
|
||||||
|
- **Use CSS variables** for consistency
|
||||||
|
- **Avoid** purple gradients on white (the "AI default")
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
--color-bg: #0a0a0a;
|
||||||
|
--color-surface: #141414;
|
||||||
|
--color-text: #fafafa;
|
||||||
|
--color-accent: #ff4d00;
|
||||||
|
--color-muted: #666666;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Spatial Composition
|
||||||
|
|
||||||
|
Break expectations:
|
||||||
|
- **Asymmetry** over perfect balance
|
||||||
|
- **Overlap** elements intentionally
|
||||||
|
- **Diagonal flow** or unconventional layouts
|
||||||
|
- **Generous negative space** OR controlled density — not middle ground
|
||||||
|
- **Grid-breaking elements** that draw attention
|
||||||
|
|
||||||
|
### Motion & Interaction
|
||||||
|
|
||||||
|
Focus on high-impact moments:
|
||||||
|
- **Page load**: Staggered reveals with `animation-delay`
|
||||||
|
- **Scroll-triggered** animations that surprise
|
||||||
|
- **Hover states** with personality
|
||||||
|
- Prefer **CSS animations** for HTML; **Motion library** for React
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* Staggered entrance */
|
||||||
|
.card { animation: fadeUp 0.6s ease-out backwards; }
|
||||||
|
.card:nth-child(1) { animation-delay: 0.1s; }
|
||||||
|
.card:nth-child(2) { animation-delay: 0.2s; }
|
||||||
|
.card:nth-child(3) { animation-delay: 0.3s; }
|
||||||
|
|
||||||
|
@keyframes fadeUp {
|
||||||
|
from { opacity: 0; transform: translateY(20px); }
|
||||||
|
to { opacity: 1; transform: translateY(0); }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Backgrounds & Atmosphere
|
||||||
|
|
||||||
|
Create depth and atmosphere:
|
||||||
|
- **Gradient meshes** and multi-stop gradients
|
||||||
|
- **Noise textures** and grain overlays
|
||||||
|
- **Geometric patterns** or subtle grids
|
||||||
|
- **Layered transparencies**
|
||||||
|
- **Dramatic shadows** or complete flatness
|
||||||
|
- **Custom cursors** for interactive elements
|
||||||
|
|
||||||
|
## Implementation Principles
|
||||||
|
|
||||||
|
### Match Complexity to Vision
|
||||||
|
|
||||||
|
- **Maximalist vision** → elaborate code with extensive animations
|
||||||
|
- **Minimalist vision** → restraint, precision, perfect spacing
|
||||||
|
- Elegance = executing the vision well, not adding more
|
||||||
|
|
||||||
|
### Vary Between Generations
|
||||||
|
|
||||||
|
Never converge on patterns:
|
||||||
|
- Alternate light/dark themes
|
||||||
|
- Use different font families each time
|
||||||
|
- Explore different aesthetic directions
|
||||||
|
- Each design should feel unique
|
||||||
|
|
||||||
|
## NEVER Do
|
||||||
|
|
||||||
|
1. **NEVER use** generic font families (Inter, Roboto, Arial, system fonts)
|
||||||
|
2. **NEVER use** purple gradients on white backgrounds — the "AI aesthetic"
|
||||||
|
3. **NEVER use** predictable, cookie-cutter layouts
|
||||||
|
4. **NEVER skip** the design thinking phase — understand before building
|
||||||
|
5. **NEVER hedge** with safe, middle-ground aesthetics — commit to a direction
|
||||||
|
6. **NEVER forget** that distinctive design requires distinctive code
|
||||||
|
7. **NEVER converge** on the same patterns across generations — vary intentionally
|
||||||
|
8. **NEVER add** complexity without purpose — minimalism and maximalism both require intention
|
||||||
2410
.opencode/skills/frontend-developer/react/AGENTS.md
Normal file
2410
.opencode/skills/frontend-developer/react/AGENTS.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,55 @@
|
|||||||
|
---
|
||||||
|
title: Store Event Handlers in Refs
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: stable subscriptions
|
||||||
|
tags: advanced, hooks, refs, event-handlers, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Store Event Handlers in Refs
|
||||||
|
|
||||||
|
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||||
|
|
||||||
|
**Incorrect (re-subscribes on every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener(event, handler)
|
||||||
|
return () => window.removeEventListener(event, handler)
|
||||||
|
}, [event, handler])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (stable subscription):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
const handlerRef = useRef(handler)
|
||||||
|
useEffect(() => {
|
||||||
|
handlerRef.current = handler
|
||||||
|
}, [handler])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const listener = () => handlerRef.current()
|
||||||
|
window.addEventListener(event, listener)
|
||||||
|
return () => window.removeEventListener(event, listener)
|
||||||
|
}, [event])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useEffectEvent } from 'react'
|
||||||
|
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
const onEvent = useEffectEvent(handler)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener(event, onEvent)
|
||||||
|
return () => window.removeEventListener(event, onEvent)
|
||||||
|
}, [event])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: useLatest for Stable Callback Refs
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: prevents effect re-runs
|
||||||
|
tags: advanced, hooks, useLatest, refs, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## useLatest for Stable Callback Refs
|
||||||
|
|
||||||
|
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function useLatest<T>(value: T) {
|
||||||
|
const ref = useRef(value)
|
||||||
|
useEffect(() => {
|
||||||
|
ref.current = value
|
||||||
|
}, [value])
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Incorrect (effect re-runs on every callback change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => onSearch(query), 300)
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
}, [query, onSearch])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (stable effect, fresh callback):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
const onSearchRef = useLatest(onSearch)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => onSearchRef.current(query), 300)
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
}, [query])
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: Prevent Waterfall Chains in API Routes
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: api-routes, server-actions, waterfalls, parallelization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prevent Waterfall Chains in API Routes
|
||||||
|
|
||||||
|
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||||
|
|
||||||
|
**Incorrect (config waits for auth, data waits for both):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
const config = await fetchConfig()
|
||||||
|
const data = await fetchData(session.user.id)
|
||||||
|
return Response.json({ data, config })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (auth and config start immediately):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const sessionPromise = auth()
|
||||||
|
const configPromise = fetchConfig()
|
||||||
|
const session = await sessionPromise
|
||||||
|
const [config, data] = await Promise.all([
|
||||||
|
configPromise,
|
||||||
|
fetchData(session.user.id)
|
||||||
|
])
|
||||||
|
return Response.json({ data, config })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
title: Defer Await Until Needed
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: avoids blocking unused code paths
|
||||||
|
tags: async, await, conditional, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer Await Until Needed
|
||||||
|
|
||||||
|
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||||
|
|
||||||
|
**Incorrect (blocks both branches):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||||
|
const userData = await fetchUserData(userId)
|
||||||
|
|
||||||
|
if (skipProcessing) {
|
||||||
|
// Returns immediately but still waited for userData
|
||||||
|
return { skipped: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only this branch uses userData
|
||||||
|
return processUserData(userData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (only blocks when needed):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||||
|
if (skipProcessing) {
|
||||||
|
// Returns immediately without waiting
|
||||||
|
return { skipped: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch only when needed
|
||||||
|
const userData = await fetchUserData(userId)
|
||||||
|
return processUserData(userData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Another example (early return optimization):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Incorrect: always fetches permissions
|
||||||
|
async function updateResource(resourceId: string, userId: string) {
|
||||||
|
const permissions = await fetchPermissions(userId)
|
||||||
|
const resource = await getResource(resourceId)
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return { error: 'Not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissions.canEdit) {
|
||||||
|
return { error: 'Forbidden' }
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateResourceData(resource, permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct: fetches only when needed
|
||||||
|
async function updateResource(resourceId: string, userId: string) {
|
||||||
|
const resource = await getResource(resourceId)
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return { error: 'Not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions = await fetchPermissions(userId)
|
||||||
|
|
||||||
|
if (!permissions.canEdit) {
|
||||||
|
return { error: 'Forbidden' }
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateResourceData(resource, permissions)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
title: Dependency-Based Parallelization
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: async, parallelization, dependencies, better-all
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency-Based Parallelization
|
||||||
|
|
||||||
|
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||||
|
|
||||||
|
**Incorrect (profile waits for config unnecessarily):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [user, config] = await Promise.all([
|
||||||
|
fetchUser(),
|
||||||
|
fetchConfig()
|
||||||
|
])
|
||||||
|
const profile = await fetchProfile(user.id)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (config and profile run in parallel):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { all } from 'better-all'
|
||||||
|
|
||||||
|
const { user, config, profile } = await all({
|
||||||
|
async user() { return fetchUser() },
|
||||||
|
async config() { return fetchConfig() },
|
||||||
|
async profile() {
|
||||||
|
return fetchProfile((await this.$.user).id)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Promise.all() for Independent Operations
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: async, parallelization, promises, waterfalls
|
||||||
|
---
|
||||||
|
|
||||||
|
## Promise.all() for Independent Operations
|
||||||
|
|
||||||
|
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||||
|
|
||||||
|
**Incorrect (sequential execution, 3 round trips):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const user = await fetchUser()
|
||||||
|
const posts = await fetchPosts()
|
||||||
|
const comments = await fetchComments()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (parallel execution, 1 round trip):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [user, posts, comments] = await Promise.all([
|
||||||
|
fetchUser(),
|
||||||
|
fetchPosts(),
|
||||||
|
fetchComments()
|
||||||
|
])
|
||||||
|
```
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
---
|
||||||
|
title: Strategic Suspense Boundaries
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: faster initial paint
|
||||||
|
tags: async, suspense, streaming, layout-shift
|
||||||
|
---
|
||||||
|
|
||||||
|
## Strategic Suspense Boundaries
|
||||||
|
|
||||||
|
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||||
|
|
||||||
|
**Incorrect (wrapper blocked by data fetching):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const data = await fetchData() // Blocks entire page
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<div>
|
||||||
|
<DataDisplay data={data} />
|
||||||
|
</div>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The entire layout waits for data even though only the middle section needs it.
|
||||||
|
|
||||||
|
**Correct (wrapper shows immediately, data streams in):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Page() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<div>
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<DataDisplay />
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function DataDisplay() {
|
||||||
|
const data = await fetchData() // Only blocks this component
|
||||||
|
return <div>{data.content}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||||
|
|
||||||
|
**Alternative (share promise across components):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Page() {
|
||||||
|
// Start fetch immediately, but don't await
|
||||||
|
const dataPromise = fetchData()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<DataDisplay dataPromise={dataPromise} />
|
||||||
|
<DataSummary dataPromise={dataPromise} />
|
||||||
|
</Suspense>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||||
|
const data = use(dataPromise) // Unwraps the promise
|
||||||
|
return <div>{data.content}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||||
|
const data = use(dataPromise) // Reuses the same promise
|
||||||
|
return <div>{data.summary}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||||
|
|
||||||
|
**When NOT to use this pattern:**
|
||||||
|
|
||||||
|
- Critical data needed for layout decisions (affects positioning)
|
||||||
|
- SEO-critical content above the fold
|
||||||
|
- Small, fast queries where suspense overhead isn't worth it
|
||||||
|
- When you want to avoid layout shift (loading → content jump)
|
||||||
|
|
||||||
|
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
title: Avoid Barrel File Imports
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 200-800ms import cost, slow builds
|
||||||
|
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avoid Barrel File Imports
|
||||||
|
|
||||||
|
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||||
|
|
||||||
|
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||||
|
|
||||||
|
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||||
|
|
||||||
|
**Incorrect (imports entire library):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Check, X, Menu } from 'lucide-react'
|
||||||
|
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||||
|
// Runtime cost: 200-800ms on every cold start
|
||||||
|
|
||||||
|
import { Button, TextField } from '@mui/material'
|
||||||
|
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (imports only what you need):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import Check from 'lucide-react/dist/esm/icons/check'
|
||||||
|
import X from 'lucide-react/dist/esm/icons/x'
|
||||||
|
import Menu from 'lucide-react/dist/esm/icons/menu'
|
||||||
|
// Loads only 3 modules (~2KB vs ~1MB)
|
||||||
|
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import TextField from '@mui/material/TextField'
|
||||||
|
// Loads only what you use
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative (Next.js 13.5+):**
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js - use optimizePackageImports
|
||||||
|
module.exports = {
|
||||||
|
experimental: {
|
||||||
|
optimizePackageImports: ['lucide-react', '@mui/material']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then you can keep the ergonomic barrel imports:
|
||||||
|
import { Check, X, Menu } from 'lucide-react'
|
||||||
|
// Automatically transformed to direct imports at build time
|
||||||
|
```
|
||||||
|
|
||||||
|
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||||
|
|
||||||
|
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||||
|
|
||||||
|
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
title: Conditional Module Loading
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: loads large data only when needed
|
||||||
|
tags: bundle, conditional-loading, lazy-loading
|
||||||
|
---
|
||||||
|
|
||||||
|
## Conditional Module Loading
|
||||||
|
|
||||||
|
Load large data or modules only when a feature is activated.
|
||||||
|
|
||||||
|
**Example (lazy-load animation frames):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
|
||||||
|
const [frames, setFrames] = useState<Frame[] | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (enabled && !frames && typeof window !== 'undefined') {
|
||||||
|
import('./animation-frames.js')
|
||||||
|
.then(mod => setFrames(mod.frames))
|
||||||
|
.catch(() => setEnabled(false))
|
||||||
|
}
|
||||||
|
}, [enabled, frames, setEnabled])
|
||||||
|
|
||||||
|
if (!frames) return <Skeleton />
|
||||||
|
return <Canvas frames={frames} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: Defer Non-Critical Third-Party Libraries
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: loads after hydration
|
||||||
|
tags: bundle, third-party, analytics, defer
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer Non-Critical Third-Party Libraries
|
||||||
|
|
||||||
|
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||||
|
|
||||||
|
**Incorrect (blocks initial bundle):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Analytics } from '@vercel/analytics/react'
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<Analytics />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (loads after hydration):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const Analytics = dynamic(
|
||||||
|
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
||||||
|
{ ssr: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<Analytics />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
---
|
||||||
|
title: Dynamic Imports for Heavy Components
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: directly affects TTI and LCP
|
||||||
|
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dynamic Imports for Heavy Components
|
||||||
|
|
||||||
|
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||||
|
|
||||||
|
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { MonacoEditor } from './monaco-editor'
|
||||||
|
|
||||||
|
function CodePanel({ code }: { code: string }) {
|
||||||
|
return <MonacoEditor value={code} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (Monaco loads on demand):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const MonacoEditor = dynamic(
|
||||||
|
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
||||||
|
{ ssr: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
function CodePanel({ code }: { code: string }) {
|
||||||
|
return <MonacoEditor value={code} />
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: Preload Based on User Intent
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces perceived latency
|
||||||
|
tags: bundle, preload, user-intent, hover
|
||||||
|
---
|
||||||
|
|
||||||
|
## Preload Based on User Intent
|
||||||
|
|
||||||
|
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||||
|
|
||||||
|
**Example (preload on hover/focus):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||||
|
const preload = () => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
void import('./monaco-editor')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onMouseEnter={preload}
|
||||||
|
onFocus={preload}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
Open Editor
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example (preload when feature flag is enabled):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FlagsProvider({ children, flags }: Props) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||||
|
void import('./monaco-editor').then(mod => mod.init())
|
||||||
|
}
|
||||||
|
}, [flags.editorEnabled])
|
||||||
|
|
||||||
|
return <FlagsContext.Provider value={flags}>
|
||||||
|
{children}
|
||||||
|
</FlagsContext.Provider>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
title: Deduplicate Global Event Listeners
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: single listener for N components
|
||||||
|
tags: client, swr, event-listeners, subscription
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deduplicate Global Event Listeners
|
||||||
|
|
||||||
|
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||||
|
|
||||||
|
**Incorrect (N instances = N listeners):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.metaKey && e.key === key) {
|
||||||
|
callback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', handler)
|
||||||
|
return () => window.removeEventListener('keydown', handler)
|
||||||
|
}, [key, callback])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||||
|
|
||||||
|
**Correct (N instances = 1 listener):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import useSWRSubscription from 'swr/subscription'
|
||||||
|
|
||||||
|
// Module-level Map to track callbacks per key
|
||||||
|
const keyCallbacks = new Map<string, Set<() => void>>()
|
||||||
|
|
||||||
|
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||||
|
// Register this callback in the Map
|
||||||
|
useEffect(() => {
|
||||||
|
if (!keyCallbacks.has(key)) {
|
||||||
|
keyCallbacks.set(key, new Set())
|
||||||
|
}
|
||||||
|
keyCallbacks.get(key)!.add(callback)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
const set = keyCallbacks.get(key)
|
||||||
|
if (set) {
|
||||||
|
set.delete(callback)
|
||||||
|
if (set.size === 0) {
|
||||||
|
keyCallbacks.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [key, callback])
|
||||||
|
|
||||||
|
useSWRSubscription('global-keydown', () => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||||
|
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', handler)
|
||||||
|
return () => window.removeEventListener('keydown', handler)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function Profile() {
|
||||||
|
// Multiple shortcuts will share the same listener
|
||||||
|
useKeyboardShortcut('p', () => { /* ... */ })
|
||||||
|
useKeyboardShortcut('k', () => { /* ... */ })
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
---
|
||||||
|
title: Version and Minimize localStorage Data
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: prevents schema conflicts, reduces storage size
|
||||||
|
tags: client, localStorage, storage, versioning, data-minimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Version and Minimize localStorage Data
|
||||||
|
|
||||||
|
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// No version, stores everything, no error handling
|
||||||
|
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
|
||||||
|
const data = localStorage.getItem('userConfig')
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const VERSION = 'v2'
|
||||||
|
|
||||||
|
function saveConfig(config: { theme: string; language: string }) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
|
||||||
|
} catch {
|
||||||
|
// Throws in incognito/private browsing, quota exceeded, or disabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadConfig() {
|
||||||
|
try {
|
||||||
|
const data = localStorage.getItem(`userConfig:${VERSION}`)
|
||||||
|
return data ? JSON.parse(data) : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migration from v1 to v2
|
||||||
|
function migrate() {
|
||||||
|
try {
|
||||||
|
const v1 = localStorage.getItem('userConfig:v1')
|
||||||
|
if (v1) {
|
||||||
|
const old = JSON.parse(v1)
|
||||||
|
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
|
||||||
|
localStorage.removeItem('userConfig:v1')
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Store minimal fields from server responses:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// User object has 20+ fields, only store what UI needs
|
||||||
|
function cachePrefs(user: FullUser) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem('prefs:v1', JSON.stringify({
|
||||||
|
theme: user.preferences.theme,
|
||||||
|
notifications: user.preferences.notifications
|
||||||
|
}))
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
|
||||||
|
|
||||||
|
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
---
|
||||||
|
title: Use Passive Event Listeners for Scrolling Performance
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: eliminates scroll delay caused by event listeners
|
||||||
|
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Passive Event Listeners for Scrolling Performance
|
||||||
|
|
||||||
|
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
useEffect(() => {
|
||||||
|
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||||
|
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||||
|
|
||||||
|
document.addEventListener('touchstart', handleTouch)
|
||||||
|
document.addEventListener('wheel', handleWheel)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('touchstart', handleTouch)
|
||||||
|
document.removeEventListener('wheel', handleWheel)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
useEffect(() => {
|
||||||
|
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||||
|
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||||
|
|
||||||
|
document.addEventListener('touchstart', handleTouch, { passive: true })
|
||||||
|
document.addEventListener('wheel', handleWheel, { passive: true })
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('touchstart', handleTouch)
|
||||||
|
document.removeEventListener('wheel', handleWheel)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
```
|
||||||
|
|
||||||
|
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||||
|
|
||||||
|
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
---
|
||||||
|
title: Use SWR for Automatic Deduplication
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: automatic deduplication
|
||||||
|
tags: client, swr, deduplication, data-fetching
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use SWR for Automatic Deduplication
|
||||||
|
|
||||||
|
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||||
|
|
||||||
|
**Incorrect (no deduplication, each instance fetches):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function UserList() {
|
||||||
|
const [users, setUsers] = useState([])
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/users')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(setUsers)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (multiple instances share one request):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import useSWR from 'swr'
|
||||||
|
|
||||||
|
function UserList() {
|
||||||
|
const { data: users } = useSWR('/api/users', fetcher)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**For immutable data:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useImmutableSWR } from '@/lib/swr'
|
||||||
|
|
||||||
|
function StaticContent() {
|
||||||
|
const { data } = useImmutableSWR('/api/config', fetcher)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**For mutations:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useSWRMutation } from 'swr/mutation'
|
||||||
|
|
||||||
|
function UpdateButton() {
|
||||||
|
const { trigger } = useSWRMutation('/api/user', updateUser)
|
||||||
|
return <button onClick={() => trigger()}>Update</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Batch DOM CSS Changes
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces reflows/repaints
|
||||||
|
tags: javascript, dom, css, performance, reflow
|
||||||
|
---
|
||||||
|
|
||||||
|
## Batch DOM CSS Changes
|
||||||
|
|
||||||
|
Avoid changing styles one property at a time. Group multiple CSS changes together via classes or `cssText` to minimize browser reflows.
|
||||||
|
|
||||||
|
**Incorrect (multiple reflows):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
// Each line triggers a reflow
|
||||||
|
element.style.width = '100px'
|
||||||
|
element.style.height = '200px'
|
||||||
|
element.style.backgroundColor = 'blue'
|
||||||
|
element.style.border = '1px solid black'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (add class - single reflow):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// CSS file
|
||||||
|
.highlighted-box {
|
||||||
|
width: 100px;
|
||||||
|
height: 200px;
|
||||||
|
background-color: blue;
|
||||||
|
border: 1px solid black;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JavaScript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
element.classList.add('highlighted-box')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (change cssText - single reflow):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
element.style.cssText = `
|
||||||
|
width: 100px;
|
||||||
|
height: 200px;
|
||||||
|
background-color: blue;
|
||||||
|
border: 1px solid black;
|
||||||
|
`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**React example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Incorrect: changing styles one by one
|
||||||
|
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (ref.current && isHighlighted) {
|
||||||
|
ref.current.style.width = '100px'
|
||||||
|
ref.current.style.height = '200px'
|
||||||
|
ref.current.style.backgroundColor = 'blue'
|
||||||
|
}
|
||||||
|
}, [isHighlighted])
|
||||||
|
|
||||||
|
return <div ref={ref}>Content</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct: toggle class
|
||||||
|
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
||||||
|
Content
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Prefer CSS classes over inline styles when possible. Classes are cached by the browser and provide better separation of concerns.
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
title: Cache Repeated Function Calls
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoid redundant computation
|
||||||
|
tags: javascript, cache, memoization, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Repeated Function Calls
|
||||||
|
|
||||||
|
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||||
|
|
||||||
|
**Incorrect (redundant computation):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function ProjectList({ projects }: { projects: Project[] }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{projects.map(project => {
|
||||||
|
// slugify() called 100+ times for same project names
|
||||||
|
const slug = slugify(project.name)
|
||||||
|
|
||||||
|
return <ProjectCard key={project.id} slug={slug} />
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (cached results):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Module-level cache
|
||||||
|
const slugifyCache = new Map<string, string>()
|
||||||
|
|
||||||
|
function cachedSlugify(text: string): string {
|
||||||
|
if (slugifyCache.has(text)) {
|
||||||
|
return slugifyCache.get(text)!
|
||||||
|
}
|
||||||
|
const result = slugify(text)
|
||||||
|
slugifyCache.set(text, result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectList({ projects }: { projects: Project[] }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{projects.map(project => {
|
||||||
|
// Computed only once per unique project name
|
||||||
|
const slug = cachedSlugify(project.name)
|
||||||
|
|
||||||
|
return <ProjectCard key={project.id} slug={slug} />
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Simpler pattern for single-value functions:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
let isLoggedInCache: boolean | null = null
|
||||||
|
|
||||||
|
function isLoggedIn(): boolean {
|
||||||
|
if (isLoggedInCache !== null) {
|
||||||
|
return isLoggedInCache
|
||||||
|
}
|
||||||
|
|
||||||
|
isLoggedInCache = document.cookie.includes('auth=')
|
||||||
|
return isLoggedInCache
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear cache when auth changes
|
||||||
|
function onAuthChange() {
|
||||||
|
isLoggedInCache = null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||||
|
|
||||||
|
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Cache Property Access in Loops
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces lookups
|
||||||
|
tags: javascript, loops, optimization, caching
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Property Access in Loops
|
||||||
|
|
||||||
|
Cache object property lookups in hot paths.
|
||||||
|
|
||||||
|
**Incorrect (3 lookups × N iterations):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
process(obj.config.settings.value)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 lookup total):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const value = obj.config.settings.value
|
||||||
|
const len = arr.length
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
process(value)
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
---
|
||||||
|
title: Cache Storage API Calls
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces expensive I/O
|
||||||
|
tags: javascript, localStorage, storage, caching, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Storage API Calls
|
||||||
|
|
||||||
|
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||||
|
|
||||||
|
**Incorrect (reads storage on every call):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getTheme() {
|
||||||
|
return localStorage.getItem('theme') ?? 'light'
|
||||||
|
}
|
||||||
|
// Called 10 times = 10 storage reads
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (Map cache):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const storageCache = new Map<string, string | null>()
|
||||||
|
|
||||||
|
function getLocalStorage(key: string) {
|
||||||
|
if (!storageCache.has(key)) {
|
||||||
|
storageCache.set(key, localStorage.getItem(key))
|
||||||
|
}
|
||||||
|
return storageCache.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLocalStorage(key: string, value: string) {
|
||||||
|
localStorage.setItem(key, value)
|
||||||
|
storageCache.set(key, value) // keep cache in sync
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||||
|
|
||||||
|
**Cookie caching:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
let cookieCache: Record<string, string> | null = null
|
||||||
|
|
||||||
|
function getCookie(name: string) {
|
||||||
|
if (!cookieCache) {
|
||||||
|
cookieCache = Object.fromEntries(
|
||||||
|
document.cookie.split('; ').map(c => c.split('='))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return cookieCache[name]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important (invalidate on external changes):**
|
||||||
|
|
||||||
|
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
window.addEventListener('storage', (e) => {
|
||||||
|
if (e.key) storageCache.delete(e.key)
|
||||||
|
})
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (document.visibilityState === 'visible') {
|
||||||
|
storageCache.clear()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
title: Combine Multiple Array Iterations
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces iterations
|
||||||
|
tags: javascript, arrays, loops, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Combine Multiple Array Iterations
|
||||||
|
|
||||||
|
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||||
|
|
||||||
|
**Incorrect (3 iterations):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const admins = users.filter(u => u.isAdmin)
|
||||||
|
const testers = users.filter(u => u.isTester)
|
||||||
|
const inactive = users.filter(u => !u.isActive)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 iteration):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const admins: User[] = []
|
||||||
|
const testers: User[] = []
|
||||||
|
const inactive: User[] = []
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (user.isAdmin) admins.push(user)
|
||||||
|
if (user.isTester) testers.push(user)
|
||||||
|
if (!user.isActive) inactive.push(user)
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: Early Return from Functions
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: avoids unnecessary computation
|
||||||
|
tags: javascript, functions, optimization, early-return
|
||||||
|
---
|
||||||
|
|
||||||
|
## Early Return from Functions
|
||||||
|
|
||||||
|
Return early when result is determined to skip unnecessary processing.
|
||||||
|
|
||||||
|
**Incorrect (processes all items even after finding answer):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function validateUsers(users: User[]) {
|
||||||
|
let hasError = false
|
||||||
|
let errorMessage = ''
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (!user.email) {
|
||||||
|
hasError = true
|
||||||
|
errorMessage = 'Email required'
|
||||||
|
}
|
||||||
|
if (!user.name) {
|
||||||
|
hasError = true
|
||||||
|
errorMessage = 'Name required'
|
||||||
|
}
|
||||||
|
// Continues checking all users even after error found
|
||||||
|
}
|
||||||
|
|
||||||
|
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (returns immediately on first error):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function validateUsers(users: User[]) {
|
||||||
|
for (const user of users) {
|
||||||
|
if (!user.email) {
|
||||||
|
return { valid: false, error: 'Email required' }
|
||||||
|
}
|
||||||
|
if (!user.name) {
|
||||||
|
return { valid: false, error: 'Name required' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true }
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
title: Hoist RegExp Creation
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: avoids recreation
|
||||||
|
tags: javascript, regexp, optimization, memoization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hoist RegExp Creation
|
||||||
|
|
||||||
|
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||||
|
|
||||||
|
**Incorrect (new RegExp every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Highlighter({ text, query }: Props) {
|
||||||
|
const regex = new RegExp(`(${query})`, 'gi')
|
||||||
|
const parts = text.split(regex)
|
||||||
|
return <>{parts.map((part, i) => ...)}</>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (memoize or hoist):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
|
||||||
|
function Highlighter({ text, query }: Props) {
|
||||||
|
const regex = useMemo(
|
||||||
|
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||||
|
[query]
|
||||||
|
)
|
||||||
|
const parts = text.split(regex)
|
||||||
|
return <>{parts.map((part, i) => ...)}</>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warning (global regex has mutable state):**
|
||||||
|
|
||||||
|
Global regex (`/g`) has mutable `lastIndex` state:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const regex = /foo/g
|
||||||
|
regex.test('foo') // true, lastIndex = 3
|
||||||
|
regex.test('foo') // false, lastIndex = 0
|
||||||
|
```
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
title: Build Index Maps for Repeated Lookups
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: 1M ops to 2K ops
|
||||||
|
tags: javascript, map, indexing, optimization, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Build Index Maps for Repeated Lookups
|
||||||
|
|
||||||
|
Multiple `.find()` calls by the same key should use a Map.
|
||||||
|
|
||||||
|
**Incorrect (O(n) per lookup):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function processOrders(orders: Order[], users: User[]) {
|
||||||
|
return orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
user: users.find(u => u.id === order.userId)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (O(1) per lookup):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function processOrders(orders: Order[], users: User[]) {
|
||||||
|
const userById = new Map(users.map(u => [u.id, u]))
|
||||||
|
|
||||||
|
return orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
user: userById.get(order.userId)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Build map once (O(n)), then all lookups are O(1).
|
||||||
|
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: Early Length Check for Array Comparisons
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: avoids expensive operations when lengths differ
|
||||||
|
tags: javascript, arrays, performance, optimization, comparison
|
||||||
|
---
|
||||||
|
|
||||||
|
## Early Length Check for Array Comparisons
|
||||||
|
|
||||||
|
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
||||||
|
|
||||||
|
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
||||||
|
|
||||||
|
**Incorrect (always runs expensive comparison):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function hasChanges(current: string[], original: string[]) {
|
||||||
|
// Always sorts and joins, even when lengths differ
|
||||||
|
return current.sort().join() !== original.sort().join()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
|
||||||
|
|
||||||
|
**Correct (O(1) length check first):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function hasChanges(current: string[], original: string[]) {
|
||||||
|
// Early return if lengths differ
|
||||||
|
if (current.length !== original.length) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Only sort/join when lengths match
|
||||||
|
const currentSorted = current.toSorted()
|
||||||
|
const originalSorted = original.toSorted()
|
||||||
|
for (let i = 0; i < currentSorted.length; i++) {
|
||||||
|
if (currentSorted[i] !== originalSorted[i]) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This new approach is more efficient because:
|
||||||
|
- It avoids the overhead of sorting and joining the arrays when lengths differ
|
||||||
|
- It avoids consuming memory for the joined strings (especially important for large arrays)
|
||||||
|
- It avoids mutating the original arrays
|
||||||
|
- It returns early when a difference is found
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Use Loop for Min/Max Instead of Sort
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: O(n) instead of O(n log n)
|
||||||
|
tags: javascript, arrays, performance, sorting, algorithms
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Loop for Min/Max Instead of Sort
|
||||||
|
|
||||||
|
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||||
|
|
||||||
|
**Incorrect (O(n log n) - sort to find latest):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface Project {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
updatedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLatestProject(projects: Project[]) {
|
||||||
|
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
|
||||||
|
return sorted[0]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Sorts the entire array just to find the maximum value.
|
||||||
|
|
||||||
|
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getOldestAndNewest(projects: Project[]) {
|
||||||
|
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
|
||||||
|
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Still sorts unnecessarily when only min/max are needed.
|
||||||
|
|
||||||
|
**Correct (O(n) - single loop):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getLatestProject(projects: Project[]) {
|
||||||
|
if (projects.length === 0) return null
|
||||||
|
|
||||||
|
let latest = projects[0]
|
||||||
|
|
||||||
|
for (let i = 1; i < projects.length; i++) {
|
||||||
|
if (projects[i].updatedAt > latest.updatedAt) {
|
||||||
|
latest = projects[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return latest
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOldestAndNewest(projects: Project[]) {
|
||||||
|
if (projects.length === 0) return { oldest: null, newest: null }
|
||||||
|
|
||||||
|
let oldest = projects[0]
|
||||||
|
let newest = projects[0]
|
||||||
|
|
||||||
|
for (let i = 1; i < projects.length; i++) {
|
||||||
|
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
|
||||||
|
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
return { oldest, newest }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Single pass through the array, no copying, no sorting.
|
||||||
|
|
||||||
|
**Alternative (Math.min/Math.max for small arrays):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const numbers = [5, 2, 8, 1, 9]
|
||||||
|
const min = Math.min(...numbers)
|
||||||
|
const max = Math.max(...numbers)
|
||||||
|
```
|
||||||
|
|
||||||
|
This works for small arrays but can be slower for very large arrays due to spread operator limitations. Use the loop approach for reliability.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
---
|
||||||
|
title: Use Set/Map for O(1) Lookups
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: O(n) to O(1)
|
||||||
|
tags: javascript, set, map, data-structures, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Set/Map for O(1) Lookups
|
||||||
|
|
||||||
|
Convert arrays to Set/Map for repeated membership checks.
|
||||||
|
|
||||||
|
**Incorrect (O(n) per check):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const allowedIds = ['a', 'b', 'c', ...]
|
||||||
|
items.filter(item => allowedIds.includes(item.id))
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (O(1) per check):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||||
|
items.filter(item => allowedIds.has(item.id))
|
||||||
|
```
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
---
|
||||||
|
title: Use toSorted() Instead of sort() for Immutability
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: prevents mutation bugs in React state
|
||||||
|
tags: javascript, arrays, immutability, react, state, mutation
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use toSorted() Instead of sort() for Immutability
|
||||||
|
|
||||||
|
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||||
|
|
||||||
|
**Incorrect (mutates original array):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function UserList({ users }: { users: User[] }) {
|
||||||
|
// Mutates the users prop array!
|
||||||
|
const sorted = useMemo(
|
||||||
|
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
|
[users]
|
||||||
|
)
|
||||||
|
return <div>{sorted.map(renderUser)}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (creates new array):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function UserList({ users }: { users: User[] }) {
|
||||||
|
// Creates new sorted array, original unchanged
|
||||||
|
const sorted = useMemo(
|
||||||
|
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||||
|
[users]
|
||||||
|
)
|
||||||
|
return <div>{sorted.map(renderUser)}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why this matters in React:**
|
||||||
|
|
||||||
|
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||||
|
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||||
|
|
||||||
|
**Browser support (fallback for older browsers):**
|
||||||
|
|
||||||
|
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Fallback for older browsers
|
||||||
|
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Other immutable array methods:**
|
||||||
|
|
||||||
|
- `.toSorted()` - immutable sort
|
||||||
|
- `.toReversed()` - immutable reverse
|
||||||
|
- `.toSpliced()` - immutable splice
|
||||||
|
- `.with()` - immutable element replacement
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
title: Use Activity Component for Show/Hide
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: preserves state/DOM
|
||||||
|
tags: rendering, activity, visibility, state-preservation
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Activity Component for Show/Hide
|
||||||
|
|
||||||
|
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Activity } from 'react'
|
||||||
|
|
||||||
|
function Dropdown({ isOpen }: Props) {
|
||||||
|
return (
|
||||||
|
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||||
|
<ExpensiveMenu />
|
||||||
|
</Activity>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Avoids expensive re-renders and state loss.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
---
|
||||||
|
title: Animate SVG Wrapper Instead of SVG Element
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: enables hardware acceleration
|
||||||
|
tags: rendering, svg, css, animation, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Animate SVG Wrapper Instead of SVG Element
|
||||||
|
|
||||||
|
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||||
|
|
||||||
|
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function LoadingSpinner() {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
className="animate-spin"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (animating wrapper div - hardware accelerated):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function LoadingSpinner() {
|
||||||
|
return (
|
||||||
|
<div className="animate-spin">
|
||||||
|
<svg
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
title: Use Explicit Conditional Rendering
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: prevents rendering 0 or NaN
|
||||||
|
tags: rendering, conditional, jsx, falsy-values
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Explicit Conditional Rendering
|
||||||
|
|
||||||
|
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||||
|
|
||||||
|
**Incorrect (renders "0" when count is 0):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Badge({ count }: { count: number }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{count && <span className="badge">{count}</span>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// When count = 0, renders: <div>0</div>
|
||||||
|
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (renders nothing when count is 0):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Badge({ count }: { count: number }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{count > 0 ? <span className="badge">{count}</span> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// When count = 0, renders: <div></div>
|
||||||
|
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||||
|
```
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: CSS content-visibility for Long Lists
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: faster initial render
|
||||||
|
tags: rendering, css, content-visibility, long-lists
|
||||||
|
---
|
||||||
|
|
||||||
|
## CSS content-visibility for Long Lists
|
||||||
|
|
||||||
|
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||||
|
|
||||||
|
**CSS:**
|
||||||
|
|
||||||
|
```css
|
||||||
|
.message-item {
|
||||||
|
content-visibility: auto;
|
||||||
|
contain-intrinsic-size: 0 80px;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function MessageList({ messages }: { messages: Message[] }) {
|
||||||
|
return (
|
||||||
|
<div className="overflow-y-auto h-screen">
|
||||||
|
{messages.map(msg => (
|
||||||
|
<div key={msg.id} className="message-item">
|
||||||
|
<Avatar user={msg.author} />
|
||||||
|
<div>{msg.content}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
---
|
||||||
|
title: Hoist Static JSX Elements
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: avoids re-creation
|
||||||
|
tags: rendering, jsx, static, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hoist Static JSX Elements
|
||||||
|
|
||||||
|
Extract static JSX outside components to avoid re-creation.
|
||||||
|
|
||||||
|
**Incorrect (recreates element every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function LoadingSkeleton() {
|
||||||
|
return <div className="animate-pulse h-20 bg-gray-200" />
|
||||||
|
}
|
||||||
|
|
||||||
|
function Container() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{loading && <LoadingSkeleton />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (reuses same element):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const loadingSkeleton = (
|
||||||
|
<div className="animate-pulse h-20 bg-gray-200" />
|
||||||
|
)
|
||||||
|
|
||||||
|
function Container() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{loading && loadingSkeleton}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
||||||
|
|
||||||
|
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Prevent Hydration Mismatch Without Flickering
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoids visual flicker and hydration errors
|
||||||
|
tags: rendering, ssr, hydration, localStorage, flicker
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prevent Hydration Mismatch Without Flickering
|
||||||
|
|
||||||
|
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
|
||||||
|
|
||||||
|
**Incorrect (breaks SSR):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||||
|
// localStorage is not available on server - throws error
|
||||||
|
const theme = localStorage.getItem('theme') || 'light'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={theme}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Server-side rendering will fail because `localStorage` is undefined.
|
||||||
|
|
||||||
|
**Incorrect (visual flickering):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||||
|
const [theme, setTheme] = useState('light')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Runs after hydration - causes visible flash
|
||||||
|
const stored = localStorage.getItem('theme')
|
||||||
|
if (stored) {
|
||||||
|
setTheme(stored)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={theme}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
||||||
|
|
||||||
|
**Correct (no flicker, no hydration mismatch):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div id="theme-wrapper">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
<script
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: `
|
||||||
|
(function() {
|
||||||
|
try {
|
||||||
|
var theme = localStorage.getItem('theme') || 'light';
|
||||||
|
var el = document.getElementById('theme-wrapper');
|
||||||
|
if (el) el.className = theme;
|
||||||
|
} catch (e) {}
|
||||||
|
})();
|
||||||
|
`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
||||||
|
|
||||||
|
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Optimize SVG Precision
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: reduces file size
|
||||||
|
tags: rendering, svg, optimization, svgo
|
||||||
|
---
|
||||||
|
|
||||||
|
## Optimize SVG Precision
|
||||||
|
|
||||||
|
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
||||||
|
|
||||||
|
**Incorrect (excessive precision):**
|
||||||
|
|
||||||
|
```svg
|
||||||
|
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 decimal place):**
|
||||||
|
|
||||||
|
```svg
|
||||||
|
<path d="M 10.3 20.8 L 30.9 40.2" />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Automate with SVGO:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx svgo --precision=1 --multipass icon.svg
|
||||||
|
```
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
---
|
||||||
|
title: Defer State Reads to Usage Point
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoids unnecessary subscriptions
|
||||||
|
tags: rerender, searchParams, localStorage, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer State Reads to Usage Point
|
||||||
|
|
||||||
|
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
||||||
|
|
||||||
|
**Incorrect (subscribes to all searchParams changes):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ShareButton({ chatId }: { chatId: string }) {
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
|
||||||
|
const handleShare = () => {
|
||||||
|
const ref = searchParams.get('ref')
|
||||||
|
shareChat(chatId, { ref })
|
||||||
|
}
|
||||||
|
|
||||||
|
return <button onClick={handleShare}>Share</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (reads on demand, no subscription):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ShareButton({ chatId }: { chatId: string }) {
|
||||||
|
const handleShare = () => {
|
||||||
|
const params = new URLSearchParams(window.location.search)
|
||||||
|
const ref = params.get('ref')
|
||||||
|
shareChat(chatId, { ref })
|
||||||
|
}
|
||||||
|
|
||||||
|
return <button onClick={handleShare}>Share</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
title: Narrow Effect Dependencies
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: minimizes effect re-runs
|
||||||
|
tags: rerender, useEffect, dependencies, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Narrow Effect Dependencies
|
||||||
|
|
||||||
|
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
||||||
|
|
||||||
|
**Incorrect (re-runs on any user field change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
useEffect(() => {
|
||||||
|
console.log(user.id)
|
||||||
|
}, [user])
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (re-runs only when id changes):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
useEffect(() => {
|
||||||
|
console.log(user.id)
|
||||||
|
}, [user.id])
|
||||||
|
```
|
||||||
|
|
||||||
|
**For derived state, compute outside effect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Incorrect: runs on width=767, 766, 765...
|
||||||
|
useEffect(() => {
|
||||||
|
if (width < 768) {
|
||||||
|
enableMobileMode()
|
||||||
|
}
|
||||||
|
}, [width])
|
||||||
|
|
||||||
|
// Correct: runs only on boolean transition
|
||||||
|
const isMobile = width < 768
|
||||||
|
useEffect(() => {
|
||||||
|
if (isMobile) {
|
||||||
|
enableMobileMode()
|
||||||
|
}
|
||||||
|
}, [isMobile])
|
||||||
|
```
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
title: Subscribe to Derived State
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces re-render frequency
|
||||||
|
tags: rerender, derived-state, media-query, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Subscribe to Derived State
|
||||||
|
|
||||||
|
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
||||||
|
|
||||||
|
**Incorrect (re-renders on every pixel change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Sidebar() {
|
||||||
|
const width = useWindowWidth() // updates continuously
|
||||||
|
const isMobile = width < 768
|
||||||
|
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (re-renders only when boolean changes):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Sidebar() {
|
||||||
|
const isMobile = useMediaQuery('(max-width: 767px)')
|
||||||
|
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
title: Use Functional setState Updates
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: prevents stale closures and unnecessary callback recreations
|
||||||
|
tags: react, hooks, useState, useCallback, callbacks, closures
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Functional setState Updates
|
||||||
|
|
||||||
|
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
|
||||||
|
|
||||||
|
**Incorrect (requires state as dependency):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function TodoList() {
|
||||||
|
const [items, setItems] = useState(initialItems)
|
||||||
|
|
||||||
|
// Callback must depend on items, recreated on every items change
|
||||||
|
const addItems = useCallback((newItems: Item[]) => {
|
||||||
|
setItems([...items, ...newItems])
|
||||||
|
}, [items]) // ❌ items dependency causes recreations
|
||||||
|
|
||||||
|
// Risk of stale closure if dependency is forgotten
|
||||||
|
const removeItem = useCallback((id: string) => {
|
||||||
|
setItems(items.filter(item => item.id !== id))
|
||||||
|
}, []) // ❌ Missing items dependency - will use stale items!
|
||||||
|
|
||||||
|
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
|
||||||
|
|
||||||
|
**Correct (stable callbacks, no stale closures):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function TodoList() {
|
||||||
|
const [items, setItems] = useState(initialItems)
|
||||||
|
|
||||||
|
// Stable callback, never recreated
|
||||||
|
const addItems = useCallback((newItems: Item[]) => {
|
||||||
|
setItems(curr => [...curr, ...newItems])
|
||||||
|
}, []) // ✅ No dependencies needed
|
||||||
|
|
||||||
|
// Always uses latest state, no stale closure risk
|
||||||
|
const removeItem = useCallback((id: string) => {
|
||||||
|
setItems(curr => curr.filter(item => item.id !== id))
|
||||||
|
}, []) // ✅ Safe and stable
|
||||||
|
|
||||||
|
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Benefits:**
|
||||||
|
|
||||||
|
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
||||||
|
2. **No stale closures** - Always operates on the latest state value
|
||||||
|
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
||||||
|
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
||||||
|
|
||||||
|
**When to use functional updates:**
|
||||||
|
|
||||||
|
- Any setState that depends on the current state value
|
||||||
|
- Inside useCallback/useMemo when state is needed
|
||||||
|
- Event handlers that reference state
|
||||||
|
- Async operations that update state
|
||||||
|
|
||||||
|
**When direct updates are fine:**
|
||||||
|
|
||||||
|
- Setting state to a static value: `setCount(0)`
|
||||||
|
- Setting state from props/arguments only: `setName(newName)`
|
||||||
|
- State doesn't depend on previous value
|
||||||
|
|
||||||
|
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
---
|
||||||
|
title: Use Lazy State Initialization
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: wasted computation on every render
|
||||||
|
tags: react, hooks, useState, performance, initialization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Lazy State Initialization
|
||||||
|
|
||||||
|
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
||||||
|
|
||||||
|
**Incorrect (runs on every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FilteredList({ items }: { items: Item[] }) {
|
||||||
|
// buildSearchIndex() runs on EVERY render, even after initialization
|
||||||
|
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
// When query changes, buildSearchIndex runs again unnecessarily
|
||||||
|
return <SearchResults index={searchIndex} query={query} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function UserProfile() {
|
||||||
|
// JSON.parse runs on every render
|
||||||
|
const [settings, setSettings] = useState(
|
||||||
|
JSON.parse(localStorage.getItem('settings') || '{}')
|
||||||
|
)
|
||||||
|
|
||||||
|
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (runs only once):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FilteredList({ items }: { items: Item[] }) {
|
||||||
|
// buildSearchIndex() runs ONLY on initial render
|
||||||
|
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
return <SearchResults index={searchIndex} query={query} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function UserProfile() {
|
||||||
|
// JSON.parse runs only on initial render
|
||||||
|
const [settings, setSettings] = useState(() => {
|
||||||
|
const stored = localStorage.getItem('settings')
|
||||||
|
return stored ? JSON.parse(stored) : {}
|
||||||
|
})
|
||||||
|
|
||||||
|
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
||||||
|
|
||||||
|
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
title: Extract to Memoized Components
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: enables early returns
|
||||||
|
tags: rerender, memo, useMemo, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Extract to Memoized Components
|
||||||
|
|
||||||
|
Extract expensive work into memoized components to enable early returns before computation.
|
||||||
|
|
||||||
|
**Incorrect (computes avatar even when loading):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Profile({ user, loading }: Props) {
|
||||||
|
const avatar = useMemo(() => {
|
||||||
|
const id = computeAvatarId(user)
|
||||||
|
return <Avatar id={id} />
|
||||||
|
}, [user])
|
||||||
|
|
||||||
|
if (loading) return <Skeleton />
|
||||||
|
return <div>{avatar}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (skips computation when loading):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
||||||
|
const id = useMemo(() => computeAvatarId(user), [user])
|
||||||
|
return <Avatar id={id} />
|
||||||
|
})
|
||||||
|
|
||||||
|
function Profile({ user, loading }: Props) {
|
||||||
|
if (loading) return <Skeleton />
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<UserAvatar user={user} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
title: Use Transitions for Non-Urgent Updates
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: maintains UI responsiveness
|
||||||
|
tags: rerender, transitions, startTransition, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Transitions for Non-Urgent Updates
|
||||||
|
|
||||||
|
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
||||||
|
|
||||||
|
**Incorrect (blocks UI on every scroll):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ScrollTracker() {
|
||||||
|
const [scrollY, setScrollY] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => setScrollY(window.scrollY)
|
||||||
|
window.addEventListener('scroll', handler, { passive: true })
|
||||||
|
return () => window.removeEventListener('scroll', handler)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (non-blocking updates):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { startTransition } from 'react'
|
||||||
|
|
||||||
|
function ScrollTracker() {
|
||||||
|
const [scrollY, setScrollY] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => {
|
||||||
|
startTransition(() => setScrollY(window.scrollY))
|
||||||
|
}
|
||||||
|
window.addEventListener('scroll', handler, { passive: true })
|
||||||
|
return () => window.removeEventListener('scroll', handler)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
---
|
||||||
|
title: Use after() for Non-Blocking Operations
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: faster response times
|
||||||
|
tags: server, async, logging, analytics, side-effects
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use after() for Non-Blocking Operations
|
||||||
|
|
||||||
|
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
||||||
|
|
||||||
|
**Incorrect (blocks response):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { logUserAction } from '@/app/utils'
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
// Perform mutation
|
||||||
|
await updateDatabase(request)
|
||||||
|
|
||||||
|
// Logging blocks the response
|
||||||
|
const userAgent = request.headers.get('user-agent') || 'unknown'
|
||||||
|
await logUserAction({ userAgent })
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ status: 'success' }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (non-blocking):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { after } from 'next/server'
|
||||||
|
import { headers, cookies } from 'next/headers'
|
||||||
|
import { logUserAction } from '@/app/utils'
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
// Perform mutation
|
||||||
|
await updateDatabase(request)
|
||||||
|
|
||||||
|
// Log after response is sent
|
||||||
|
after(async () => {
|
||||||
|
const userAgent = (await headers()).get('user-agent') || 'unknown'
|
||||||
|
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
|
||||||
|
|
||||||
|
logUserAction({ sessionCookie, userAgent })
|
||||||
|
})
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ status: 'success' }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The response is sent immediately while logging happens in the background.
|
||||||
|
|
||||||
|
**Common use cases:**
|
||||||
|
|
||||||
|
- Analytics tracking
|
||||||
|
- Audit logging
|
||||||
|
- Sending notifications
|
||||||
|
- Cache invalidation
|
||||||
|
- Cleanup tasks
|
||||||
|
|
||||||
|
**Important notes:**
|
||||||
|
|
||||||
|
- `after()` runs even if the response fails or redirects
|
||||||
|
- Works in Server Actions, Route Handlers, and Server Components
|
||||||
|
|
||||||
|
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
---
|
||||||
|
title: Cross-Request LRU Caching
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: caches across requests
|
||||||
|
tags: server, cache, lru, cross-request
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cross-Request LRU Caching
|
||||||
|
|
||||||
|
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { LRUCache } from 'lru-cache'
|
||||||
|
|
||||||
|
const cache = new LRUCache<string, any>({
|
||||||
|
max: 1000,
|
||||||
|
ttl: 5 * 60 * 1000 // 5 minutes
|
||||||
|
})
|
||||||
|
|
||||||
|
export async function getUser(id: string) {
|
||||||
|
const cached = cache.get(id)
|
||||||
|
if (cached) return cached
|
||||||
|
|
||||||
|
const user = await db.user.findUnique({ where: { id } })
|
||||||
|
cache.set(id, user)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request 1: DB query, result cached
|
||||||
|
// Request 2: cache hit, no DB query
|
||||||
|
```
|
||||||
|
|
||||||
|
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
||||||
|
|
||||||
|
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
||||||
|
|
||||||
|
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
||||||
|
|
||||||
|
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
---
|
||||||
|
title: Per-Request Deduplication with React.cache()
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: deduplicates within request
|
||||||
|
tags: server, cache, react-cache, deduplication
|
||||||
|
---
|
||||||
|
|
||||||
|
## Per-Request Deduplication with React.cache()
|
||||||
|
|
||||||
|
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { cache } from 'react'
|
||||||
|
|
||||||
|
export const getCurrentUser = cache(async () => {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
return await db.user.findUnique({
|
||||||
|
where: { id: session.user.id }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
||||||
|
|
||||||
|
**Avoid inline objects as arguments:**
|
||||||
|
|
||||||
|
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
|
||||||
|
|
||||||
|
**Incorrect (always cache miss):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const getUser = cache(async (params: { uid: number }) => {
|
||||||
|
return await db.user.findUnique({ where: { id: params.uid } })
|
||||||
|
})
|
||||||
|
|
||||||
|
// Each call creates new object, never hits cache
|
||||||
|
getUser({ uid: 1 })
|
||||||
|
getUser({ uid: 1 }) // Cache miss, runs query again
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (cache hit):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const getUser = cache(async (uid: number) => {
|
||||||
|
return await db.user.findUnique({ where: { id: uid } })
|
||||||
|
})
|
||||||
|
|
||||||
|
// Primitive args use value equality
|
||||||
|
getUser(1)
|
||||||
|
getUser(1) // Cache hit, returns cached result
|
||||||
|
```
|
||||||
|
|
||||||
|
If you must pass objects, pass the same reference:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const params = { uid: 1 }
|
||||||
|
getUser(params) // Query runs
|
||||||
|
getUser(params) // Cache hit (same reference)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Next.js-Specific Note:**
|
||||||
|
|
||||||
|
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
|
||||||
|
|
||||||
|
- Database queries (Prisma, Drizzle, etc.)
|
||||||
|
- Heavy computations
|
||||||
|
- Authentication checks
|
||||||
|
- File system operations
|
||||||
|
- Any non-fetch async work
|
||||||
|
|
||||||
|
Use `React.cache()` to deduplicate these operations across your component tree.
|
||||||
|
|
||||||
|
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
---
|
||||||
|
title: Parallel Data Fetching with Component Composition
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: eliminates server-side waterfalls
|
||||||
|
tags: server, rsc, parallel-fetching, composition
|
||||||
|
---
|
||||||
|
|
||||||
|
## Parallel Data Fetching with Component Composition
|
||||||
|
|
||||||
|
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
||||||
|
|
||||||
|
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default async function Page() {
|
||||||
|
const header = await fetchHeader()
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>{header}</div>
|
||||||
|
<Sidebar />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Sidebar() {
|
||||||
|
const items = await fetchSidebarItems()
|
||||||
|
return <nav>{items.map(renderItem)}</nav>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (both fetch simultaneously):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Header() {
|
||||||
|
const data = await fetchHeader()
|
||||||
|
return <div>{data}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Sidebar() {
|
||||||
|
const items = await fetchSidebarItems()
|
||||||
|
return <nav>{items.map(renderItem)}</nav>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Header />
|
||||||
|
<Sidebar />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative with children prop:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Header() {
|
||||||
|
const data = await fetchHeader()
|
||||||
|
return <div>{data}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Sidebar() {
|
||||||
|
const items = await fetchSidebarItems()
|
||||||
|
return <nav>{items.map(renderItem)}</nav>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Layout({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Header />
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return (
|
||||||
|
<Layout>
|
||||||
|
<Sidebar />
|
||||||
|
</Layout>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: Minimize Serialization at RSC Boundaries
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: reduces data transfer size
|
||||||
|
tags: server, rsc, serialization, props
|
||||||
|
---
|
||||||
|
|
||||||
|
## Minimize Serialization at RSC Boundaries
|
||||||
|
|
||||||
|
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
||||||
|
|
||||||
|
**Incorrect (serializes all 50 fields):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const user = await fetchUser() // 50 fields
|
||||||
|
return <Profile user={user} />
|
||||||
|
}
|
||||||
|
|
||||||
|
'use client'
|
||||||
|
function Profile({ user }: { user: User }) {
|
||||||
|
return <div>{user.name}</div> // uses 1 field
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (serializes only 1 field):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const user = await fetchUser()
|
||||||
|
return <Profile name={user.name} />
|
||||||
|
}
|
||||||
|
|
||||||
|
'use client'
|
||||||
|
function Profile({ name }: { name: string }) {
|
||||||
|
return <div>{name}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
52
.opencode/skills/frontend-developer/references/angular.md
Normal file
52
.opencode/skills/frontend-developer/references/angular.md
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
# Modern Angular Architecture
|
||||||
|
|
||||||
|
**Status**: Definitive Guide
|
||||||
|
**Stack**: Angular 17+
|
||||||
|
|
||||||
|
## 🏗 Architecture: Standalone & Zone-less
|
||||||
|
|
||||||
|
### 1. Standalone Components
|
||||||
|
|
||||||
|
- **Ban**: `NgModule` (unless for legacy libs).
|
||||||
|
- **Enforce**: `standalone: true` in all components, directives, and pipes.
|
||||||
|
- **Why**: Tree-shaking, easier testing, simplified learning curve.
|
||||||
|
|
||||||
|
### 2. Signals (State Management)
|
||||||
|
|
||||||
|
- **Signals over Observables**: Use Signals for synchronous state. Use RxJS ONLY for complex asynchronous event streams (debounce, switchMap).
|
||||||
|
- **Ban**: `Zone.js` (eventually). Prepare for zoneless by using `ChangeDetectionStrategy.OnPush` everywhere.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ GOOD: Signal
|
||||||
|
@Component({ ... changeDetection: ChangeDetectionStrategy.OnPush })
|
||||||
|
export class Counter {
|
||||||
|
count = signal(0);
|
||||||
|
double = computed(() => this.count() * 2);
|
||||||
|
|
||||||
|
increment() {
|
||||||
|
this.count.update(c => c + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Control Flow Syntax
|
||||||
|
|
||||||
|
- **Use**: `@if`, `@for`, `@switch`.
|
||||||
|
- **Ban**: `*ngIf`, `*ngFor` (legacy structural directives).
|
||||||
|
|
||||||
|
## ⚡ Performance Patterns
|
||||||
|
|
||||||
|
### 1. Deferrable Views
|
||||||
|
|
||||||
|
- Use `@defer` to lazy load components without routing.
|
||||||
|
- Criteria: `@defer (on viewport)` for below-the-fold content.
|
||||||
|
|
||||||
|
### 2. Hydration
|
||||||
|
|
||||||
|
- Enable Client Hydration in `app.config.ts`.
|
||||||
|
- Avoid direct DOM manipulation which breaks hydration.
|
||||||
|
|
||||||
|
## 🧪 Testing
|
||||||
|
|
||||||
|
- **Harnesses**: Use Component Harnesses for robust tests.
|
||||||
|
- **Signals**: Test signals by verifying computed outputs.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Core Performance & Accessibility Standards
|
||||||
|
|
||||||
|
**Status**: Mandaory
|
||||||
|
**Applies To**: ALL Frameworks (React, Vue, Angular, Svelte, etc.)
|
||||||
|
|
||||||
|
## 🚀 Performance: The "Zero-Overhead" Standard
|
||||||
|
|
||||||
|
### 1. Core Web Vitals (The Holy Trinity)
|
||||||
|
|
||||||
|
You must optimize for these metrics _before_ writing business logic.
|
||||||
|
|
||||||
|
- **LCP (Largest Contentful Paint)**: < 2.5s
|
||||||
|
- **Strategy**: The LCP element (usually Hero Image or H1) must be in the initial HTML.
|
||||||
|
- **Ban**: Never lazy-load the LCP image. Never use client-side rendering for the LCP element.
|
||||||
|
- **Code**: `<img fetchpriority="high" decoding="sync" ... />`
|
||||||
|
|
||||||
|
- **INP (Interaction to Next Paint)**: < 200ms
|
||||||
|
- **Strategy**: Break up long tasks.
|
||||||
|
- **Ban**: `useEffect` or watchers that run heavy computation on input. Yield to main thread (`scheduler.yield()` or `setTimeout(..., 0)`).
|
||||||
|
|
||||||
|
- **CLS (Cumulative Layout Shift)**: < 0.1
|
||||||
|
- **Strategy**: Rigidly defined dimensions for all media and containers.
|
||||||
|
- **Ban**: Images without `width/height`. Ad containers without `min-height`.
|
||||||
|
|
||||||
|
### 2. Bundle Analysis
|
||||||
|
|
||||||
|
- **Budget**: Initial JS < 50KB (gzip).
|
||||||
|
- **Tree-Shaking**: Import specific functions, not whole libraries.
|
||||||
|
- ✅ `import { map } from 'lodash-es'`
|
||||||
|
- ❌ `import _ from 'lodash'`
|
||||||
|
- **Splitting**: Route-level splitting is mandatory. Component-level splitting for heavy interactions (modals, charts).
|
||||||
|
|
||||||
|
### 3. Image Optimization
|
||||||
|
|
||||||
|
- **Formats**: AVIF > WebP > JPG/PNG.
|
||||||
|
- **Responsive**: Use `srcset` and `sizes`.
|
||||||
|
- **Lazy**: `loading="lazy"` for everything below the fold.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ♿ Accessibility: The "Keyboard First" Standard
|
||||||
|
|
||||||
|
**Rule**: If you can't use it with `Tab` + `Enter`/`Space`, it is broken.
|
||||||
|
|
||||||
|
### 1. Semantic HTML
|
||||||
|
|
||||||
|
- **Buttons**: Use `<button>`, not `<div onClick>`.
|
||||||
|
- **Links**: Use `<a>` with `href`, not `<button onClick="go()">`.
|
||||||
|
- **Landmarks**: `<main>`, `<nav>`, `<aside>`, `<header>`, `<footer>`.
|
||||||
|
|
||||||
|
### 2. Focus Management
|
||||||
|
|
||||||
|
- **Visible Focus**: Never remove `outline` without replacing it with a custom high-contrast focus style.
|
||||||
|
- **Trap Focus**: Modals must trap focus inside them.
|
||||||
|
|
||||||
|
### 3. ARIA (Last Resort)
|
||||||
|
|
||||||
|
- Use ARIA only when HTML is insufficient.
|
||||||
|
- **No ARIA > Bad ARIA**.
|
||||||
|
- **Images**: `alt=""` for decorative, descriptive text for informational.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔒 Security Basics
|
||||||
|
|
||||||
|
- **XSS**: Sanitize all `innerHTML`.
|
||||||
|
- **Deps**: Audit `npm audit` regularly.
|
||||||
|
- **HTTPS**: Enforce HSTS.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Modern Signals & Fine-Grained Reactivity
|
||||||
|
|
||||||
|
**Stack**: Svelte 5 (Runes), SolidJS, Qwik
|
||||||
|
|
||||||
|
## 🧠 The Philosophy: "No Virtual DOM"
|
||||||
|
|
||||||
|
Unlike React/Vue, these frameworks target the DOM directly.
|
||||||
|
|
||||||
|
- **Fine-Grained**: Only the text node that changes updates. No component re-renders.
|
||||||
|
- **Mental Model**: Code runs _once_ (setup), then reactivity takes over.
|
||||||
|
|
||||||
|
## 🧱 Framework specifics
|
||||||
|
|
||||||
|
### Svelte 5 (Runes)
|
||||||
|
|
||||||
|
- **State**: `let count = $state(0)`
|
||||||
|
- **Derived**: `let double = $derived(count * 2)`
|
||||||
|
- **Side Effects**: `$effect(() => ...)`
|
||||||
|
- **Snippets**: Replace slots with `{#snippet}`.
|
||||||
|
|
||||||
|
### SolidJS
|
||||||
|
|
||||||
|
- **Read/Write Split**: `const [count, setCount] = createSignal(0)`
|
||||||
|
- **DOM Access**: strictly in `onMount`.
|
||||||
|
- **Control Flow**: Use `<Show>`, `<For>` (don't use map).
|
||||||
|
|
||||||
|
### Qwik (Resumability)
|
||||||
|
|
||||||
|
- **The Golden Rule**: Do not execute JS on the client unless checking an event.
|
||||||
|
- **Serialized State**: All state must be serializable (JSON).
|
||||||
|
- **$**: The optimizer barrier. `onClick$`, `useSignal$`.
|
||||||
|
|
||||||
|
## ⚡ Performance Targets
|
||||||
|
|
||||||
|
1. **Hydration**:
|
||||||
|
- **Svelte/Solid**: Fast hydration.
|
||||||
|
- **Qwik**: No hydration (Resumability).
|
||||||
|
2. **Closures**: Avoid creating closures in render loops (except Qwik where `$` handles it).
|
||||||
|
|
||||||
|
## 🧪 Testing
|
||||||
|
|
||||||
|
- **E2E**: Playwright is the gold standard for all three.
|
||||||
|
- **Unit**: Vitest.
|
||||||
55
.opencode/skills/frontend-developer/references/vue-nuxt.md
Normal file
55
.opencode/skills/frontend-developer/references/vue-nuxt.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
# Vue & Nuxt 3 Architecture
|
||||||
|
|
||||||
|
**Status**: Definitive Guide
|
||||||
|
**Stack**: Vue 3 (Composition API), Nuxt 3
|
||||||
|
|
||||||
|
## 🏗 Architecture: Composition & Modules
|
||||||
|
|
||||||
|
### 1. Composition API Only
|
||||||
|
|
||||||
|
- **Ban**: Options API (`data`, `methods`).
|
||||||
|
- **Enforce**: `<script setup lang="ts">`.
|
||||||
|
- **Why**: Better TypeScript support, logic reuse via composables.
|
||||||
|
|
||||||
|
### 2. Nuxt Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
server/ # API routes (Nitro)
|
||||||
|
components/ # Auto-imported components
|
||||||
|
composables/ # Auto-imported logic
|
||||||
|
pages/ # File-based routing
|
||||||
|
layouts/ # Layouts
|
||||||
|
stores/ # Pinia definitions
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚡ Performance Patterns
|
||||||
|
|
||||||
|
### 1. Data Fetching
|
||||||
|
|
||||||
|
- **SSR-Friendly**: Use `useFetch` or `useAsyncData`.
|
||||||
|
- **Keying**: Always provide a unique key if parameters change.
|
||||||
|
- **Lazy**: `lazy: true` to prevent blocking navigation.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// ✅ GOOD
|
||||||
|
const { data, pending } = await useFetch("/api/posts", {
|
||||||
|
lazy: true,
|
||||||
|
server: false, // If client-only execution is needed
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. State Management (Pinia)
|
||||||
|
|
||||||
|
- **Setup Stores**: Use the function syntax (like `setup()`), not the object syntax.
|
||||||
|
- **Dedupe**: Don't put everything in store. Use `useState` for simple shared state.
|
||||||
|
|
||||||
|
### 3. Compute Stability
|
||||||
|
|
||||||
|
- Use `computed()` for derived state.
|
||||||
|
- Use `shallowRef()` for large objects that don't need deep reactivity.
|
||||||
|
|
||||||
|
## 🧪 Testing
|
||||||
|
|
||||||
|
- **Unit**: Vitest.
|
||||||
|
- **Component**: Vue Test Utils.
|
||||||
|
- **E2E**: Nuxt Test Utils (Playwright wrapper).
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import sys
|
||||||
|
import re
|
||||||
|
import os
|
||||||
|
|
||||||
|
def check_file(filepath):
|
||||||
|
"""
|
||||||
|
Simple heuristic checks for frontend compliance.
|
||||||
|
"""
|
||||||
|
with open(filepath, 'r') as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
errors = []
|
||||||
|
|
||||||
|
# Check 1: Image Accessibility
|
||||||
|
# Matches <img ...> without alt=
|
||||||
|
img_tags = re.findall(r'<img[^>]*>', content)
|
||||||
|
for tag in img_tags:
|
||||||
|
if 'alt=' not in tag:
|
||||||
|
errors.append(f"ACCESSIBILITY: Found <img> tag without 'alt' attribute: {tag}")
|
||||||
|
|
||||||
|
# Check 2: Next.js Image Optimization
|
||||||
|
if 'next/image' in content or '<Image' in content:
|
||||||
|
# Check for sizes prop if not fill
|
||||||
|
if '<Image' in content and 'sizes=' not in content and 'fill' not in content:
|
||||||
|
errors.append("PERFORMANCE: Found <Image> component (Next.js) without 'sizes' attribute. Use 'sizes' for responsive hydration.")
|
||||||
|
|
||||||
|
# Check 3: React Anti-Pattern (Effect Fetching)
|
||||||
|
if 'useEffect' in content and 'fetch(' in content:
|
||||||
|
errors.append("ARCHITECTURE: Found 'fetch' inside 'useEffect'. Use Server Components, React Query, or SWR instead.")
|
||||||
|
|
||||||
|
# Check 4: Angular Legacy
|
||||||
|
if '*ngIf' in content:
|
||||||
|
errors.append("MODERNIZATION: Found '*ngIf'. Use modern Angular control flow '@if'.")
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Usage: python validate_compliance.py <file_or_directory>")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
target = sys.argv[1]
|
||||||
|
all_errors = []
|
||||||
|
|
||||||
|
if os.path.isfile(target):
|
||||||
|
all_errors.extend(check_file(target))
|
||||||
|
elif os.path.isdir(target):
|
||||||
|
for root, _, files in os.walk(target):
|
||||||
|
for file in files:
|
||||||
|
if file.endswith(('.tsx', '.jsx', '.vue', '.ts', '.js')):
|
||||||
|
path = os.path.join(root, file)
|
||||||
|
all_errors.extend(check_file(path))
|
||||||
|
|
||||||
|
if all_errors:
|
||||||
|
print("❌ Compliance Errors Found:")
|
||||||
|
for err in all_errors:
|
||||||
|
print(f"- {err}")
|
||||||
|
sys.exit(1)
|
||||||
|
else:
|
||||||
|
print("✅ No obvious compliance errors found (Heuristic Check).")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
78
.opencode/skills/frontend-ui-ux/SKILL.md
Normal file
78
.opencode/skills/frontend-ui-ux/SKILL.md
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
---
|
||||||
|
name: frontend-ui-ux
|
||||||
|
description: Designer-turned-developer who crafts stunning UI/UX even without design mockups
|
||||||
|
---
|
||||||
|
|
||||||
|
# Role: Designer-Turned-Developer
|
||||||
|
|
||||||
|
You are a designer who learned to code. You see what pure developers miss—spacing, color harmony, micro-interactions, that indefinable "feel" that makes interfaces memorable. Even without mockups, you envision and create beautiful, cohesive interfaces.
|
||||||
|
|
||||||
|
**Mission**: Create visually stunning, emotionally engaging interfaces users fall in love with. Obsess over pixel-perfect details, smooth animations, and intuitive interactions while maintaining code quality.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Work Principles
|
||||||
|
|
||||||
|
1. **Complete what's asked** — Execute the exact task. No scope creep. Work until it works. Never mark work complete without proper verification.
|
||||||
|
2. **Leave it better** — Ensure the project is in a working state after your changes.
|
||||||
|
3. **Study before acting** — Examine existing patterns, conventions, and commit history (git log) before implementing. Understand why code is structured the way it is.
|
||||||
|
4. **Blend seamlessly** — Match existing code patterns. Your code should look like the team wrote it.
|
||||||
|
5. **Be transparent** — Announce each step. Explain reasoning. Report both successes and failures.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Design Process
|
||||||
|
|
||||||
|
Before coding, commit to a **BOLD aesthetic direction**:
|
||||||
|
|
||||||
|
1. **Purpose**: What problem does this solve? Who uses it?
|
||||||
|
2. **Tone**: Pick an extreme—brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian
|
||||||
|
3. **Constraints**: Technical requirements (framework, performance, accessibility)
|
||||||
|
4. **Differentiation**: What's the ONE thing someone will remember?
|
||||||
|
|
||||||
|
**Key**: Choose a clear direction and execute with precision. Intentionality > intensity.
|
||||||
|
|
||||||
|
Then implement working code (HTML/CSS/JS, React, Vue, Angular, etc.) that is:
|
||||||
|
- Production-grade and functional
|
||||||
|
- Visually striking and memorable
|
||||||
|
- Cohesive with a clear aesthetic point-of-view
|
||||||
|
- Meticulously refined in every detail
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Aesthetic Guidelines
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
Choose distinctive fonts. **Avoid**: Arial, Inter, Roboto, system fonts, Space Grotesk. Pair a characterful display font with a refined body font.
|
||||||
|
|
||||||
|
## Color
|
||||||
|
Commit to a cohesive palette. Use CSS variables. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. **Avoid**: purple gradients on white (AI slop).
|
||||||
|
|
||||||
|
## Motion
|
||||||
|
Focus on high-impact moments. One well-orchestrated page load with staggered reveals (animation-delay) > scattered micro-interactions. Use scroll-triggering and hover states that surprise. Prioritize CSS-only. Use Motion library for React when available.
|
||||||
|
|
||||||
|
## Spatial Composition
|
||||||
|
Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
|
||||||
|
|
||||||
|
## Visual Details
|
||||||
|
Create atmosphere and depth—gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, grain overlays. Never default to solid colors.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Anti-Patterns (NEVER)
|
||||||
|
|
||||||
|
- Generic fonts (Inter, Roboto, Arial, system fonts, Space Grotesk)
|
||||||
|
- Cliched color schemes (purple gradients on white)
|
||||||
|
- Predictable layouts and component patterns
|
||||||
|
- Cookie-cutter design lacking context-specific character
|
||||||
|
- Converging on common choices across generations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Execution
|
||||||
|
|
||||||
|
Match implementation complexity to aesthetic vision:
|
||||||
|
- **Maximalist** → Elaborate code with extensive animations and effects
|
||||||
|
- **Minimalist** → Restraint, precision, careful spacing and typography
|
||||||
|
|
||||||
|
Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. You are capable of extraordinary creative work—don't hold back.
|
||||||
17
.opencode/skills/n8n_automation_mastery/SKILL.md
Normal file
17
.opencode/skills/n8n_automation_mastery/SKILL.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
Skill: n8n Automation Mastery
|
||||||
|
|
||||||
|
Questa skill istruisce l'agente su come interagire con l'istanza n8n locale (192.168.254.12).
|
||||||
|
|
||||||
|
Procedure Operative
|
||||||
|
|
||||||
|
Discovery: Prima di ogni operazione su n8n, usa n8n.list_workflows per identificare l'ID del workflow relativo a LogWhisperer.
|
||||||
|
|
||||||
|
Validazione: Se un workflow deve ricevere dati dallo script Bash, usa n8n.get_workflow per verificarne i nodi di ingresso (Webhook).
|
||||||
|
|
||||||
|
Test di Integrazione: Dopo aver implementato una modifica allo script Bash, usa n8n.execute_workflow per simulare la ricezione di un log e verificare che l'alert arrivi a destinazione.
|
||||||
|
|
||||||
|
Vincoli
|
||||||
|
|
||||||
|
Non eliminare workflow esistenti senza autorizzazione del @tech-lead.
|
||||||
|
|
||||||
|
Usa sempre l'ambiente di test di n8n per le prove di esecuzione.
|
||||||
2410
.opencode/skills/react/AGENTS.md
Normal file
2410
.opencode/skills/react/AGENTS.md
Normal file
File diff suppressed because it is too large
Load Diff
55
.opencode/skills/react/rules/advanced-event-handler-refs.md
Normal file
55
.opencode/skills/react/rules/advanced-event-handler-refs.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
---
|
||||||
|
title: Store Event Handlers in Refs
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: stable subscriptions
|
||||||
|
tags: advanced, hooks, refs, event-handlers, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Store Event Handlers in Refs
|
||||||
|
|
||||||
|
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||||
|
|
||||||
|
**Incorrect (re-subscribes on every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener(event, handler)
|
||||||
|
return () => window.removeEventListener(event, handler)
|
||||||
|
}, [event, handler])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (stable subscription):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
const handlerRef = useRef(handler)
|
||||||
|
useEffect(() => {
|
||||||
|
handlerRef.current = handler
|
||||||
|
}, [handler])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const listener = () => handlerRef.current()
|
||||||
|
window.addEventListener(event, listener)
|
||||||
|
return () => window.removeEventListener(event, listener)
|
||||||
|
}, [event])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useEffectEvent } from 'react'
|
||||||
|
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
const onEvent = useEffectEvent(handler)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener(event, onEvent)
|
||||||
|
return () => window.removeEventListener(event, onEvent)
|
||||||
|
}, [event])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||||
49
.opencode/skills/react/rules/advanced-use-latest.md
Normal file
49
.opencode/skills/react/rules/advanced-use-latest.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: useLatest for Stable Callback Refs
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: prevents effect re-runs
|
||||||
|
tags: advanced, hooks, useLatest, refs, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## useLatest for Stable Callback Refs
|
||||||
|
|
||||||
|
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function useLatest<T>(value: T) {
|
||||||
|
const ref = useRef(value)
|
||||||
|
useEffect(() => {
|
||||||
|
ref.current = value
|
||||||
|
}, [value])
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Incorrect (effect re-runs on every callback change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => onSearch(query), 300)
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
}, [query, onSearch])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (stable effect, fresh callback):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
const onSearchRef = useLatest(onSearch)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => onSearchRef.current(query), 300)
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
}, [query])
|
||||||
|
}
|
||||||
|
```
|
||||||
38
.opencode/skills/react/rules/async-api-routes.md
Normal file
38
.opencode/skills/react/rules/async-api-routes.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: Prevent Waterfall Chains in API Routes
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: api-routes, server-actions, waterfalls, parallelization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prevent Waterfall Chains in API Routes
|
||||||
|
|
||||||
|
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||||
|
|
||||||
|
**Incorrect (config waits for auth, data waits for both):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
const config = await fetchConfig()
|
||||||
|
const data = await fetchData(session.user.id)
|
||||||
|
return Response.json({ data, config })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (auth and config start immediately):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const sessionPromise = auth()
|
||||||
|
const configPromise = fetchConfig()
|
||||||
|
const session = await sessionPromise
|
||||||
|
const [config, data] = await Promise.all([
|
||||||
|
configPromise,
|
||||||
|
fetchData(session.user.id)
|
||||||
|
])
|
||||||
|
return Response.json({ data, config })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||||
80
.opencode/skills/react/rules/async-defer-await.md
Normal file
80
.opencode/skills/react/rules/async-defer-await.md
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
title: Defer Await Until Needed
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: avoids blocking unused code paths
|
||||||
|
tags: async, await, conditional, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer Await Until Needed
|
||||||
|
|
||||||
|
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||||
|
|
||||||
|
**Incorrect (blocks both branches):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||||
|
const userData = await fetchUserData(userId)
|
||||||
|
|
||||||
|
if (skipProcessing) {
|
||||||
|
// Returns immediately but still waited for userData
|
||||||
|
return { skipped: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only this branch uses userData
|
||||||
|
return processUserData(userData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (only blocks when needed):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||||
|
if (skipProcessing) {
|
||||||
|
// Returns immediately without waiting
|
||||||
|
return { skipped: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch only when needed
|
||||||
|
const userData = await fetchUserData(userId)
|
||||||
|
return processUserData(userData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Another example (early return optimization):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Incorrect: always fetches permissions
|
||||||
|
async function updateResource(resourceId: string, userId: string) {
|
||||||
|
const permissions = await fetchPermissions(userId)
|
||||||
|
const resource = await getResource(resourceId)
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return { error: 'Not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissions.canEdit) {
|
||||||
|
return { error: 'Forbidden' }
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateResourceData(resource, permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct: fetches only when needed
|
||||||
|
async function updateResource(resourceId: string, userId: string) {
|
||||||
|
const resource = await getResource(resourceId)
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return { error: 'Not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions = await fetchPermissions(userId)
|
||||||
|
|
||||||
|
if (!permissions.canEdit) {
|
||||||
|
return { error: 'Forbidden' }
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateResourceData(resource, permissions)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||||
36
.opencode/skills/react/rules/async-dependencies.md
Normal file
36
.opencode/skills/react/rules/async-dependencies.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
title: Dependency-Based Parallelization
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: async, parallelization, dependencies, better-all
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency-Based Parallelization
|
||||||
|
|
||||||
|
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||||
|
|
||||||
|
**Incorrect (profile waits for config unnecessarily):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [user, config] = await Promise.all([
|
||||||
|
fetchUser(),
|
||||||
|
fetchConfig()
|
||||||
|
])
|
||||||
|
const profile = await fetchProfile(user.id)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (config and profile run in parallel):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { all } from 'better-all'
|
||||||
|
|
||||||
|
const { user, config, profile } = await all({
|
||||||
|
async user() { return fetchUser() },
|
||||||
|
async config() { return fetchConfig() },
|
||||||
|
async profile() {
|
||||||
|
return fetchProfile((await this.$.user).id)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
||||||
28
.opencode/skills/react/rules/async-parallel.md
Normal file
28
.opencode/skills/react/rules/async-parallel.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Promise.all() for Independent Operations
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: async, parallelization, promises, waterfalls
|
||||||
|
---
|
||||||
|
|
||||||
|
## Promise.all() for Independent Operations
|
||||||
|
|
||||||
|
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||||
|
|
||||||
|
**Incorrect (sequential execution, 3 round trips):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const user = await fetchUser()
|
||||||
|
const posts = await fetchPosts()
|
||||||
|
const comments = await fetchComments()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (parallel execution, 1 round trip):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [user, posts, comments] = await Promise.all([
|
||||||
|
fetchUser(),
|
||||||
|
fetchPosts(),
|
||||||
|
fetchComments()
|
||||||
|
])
|
||||||
|
```
|
||||||
99
.opencode/skills/react/rules/async-suspense-boundaries.md
Normal file
99
.opencode/skills/react/rules/async-suspense-boundaries.md
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
---
|
||||||
|
title: Strategic Suspense Boundaries
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: faster initial paint
|
||||||
|
tags: async, suspense, streaming, layout-shift
|
||||||
|
---
|
||||||
|
|
||||||
|
## Strategic Suspense Boundaries
|
||||||
|
|
||||||
|
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||||
|
|
||||||
|
**Incorrect (wrapper blocked by data fetching):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const data = await fetchData() // Blocks entire page
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<div>
|
||||||
|
<DataDisplay data={data} />
|
||||||
|
</div>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The entire layout waits for data even though only the middle section needs it.
|
||||||
|
|
||||||
|
**Correct (wrapper shows immediately, data streams in):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Page() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<div>
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<DataDisplay />
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function DataDisplay() {
|
||||||
|
const data = await fetchData() // Only blocks this component
|
||||||
|
return <div>{data.content}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||||
|
|
||||||
|
**Alternative (share promise across components):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Page() {
|
||||||
|
// Start fetch immediately, but don't await
|
||||||
|
const dataPromise = fetchData()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<DataDisplay dataPromise={dataPromise} />
|
||||||
|
<DataSummary dataPromise={dataPromise} />
|
||||||
|
</Suspense>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||||
|
const data = use(dataPromise) // Unwraps the promise
|
||||||
|
return <div>{data.content}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||||
|
const data = use(dataPromise) // Reuses the same promise
|
||||||
|
return <div>{data.summary}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||||
|
|
||||||
|
**When NOT to use this pattern:**
|
||||||
|
|
||||||
|
- Critical data needed for layout decisions (affects positioning)
|
||||||
|
- SEO-critical content above the fold
|
||||||
|
- Small, fast queries where suspense overhead isn't worth it
|
||||||
|
- When you want to avoid layout shift (loading → content jump)
|
||||||
|
|
||||||
|
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||||
59
.opencode/skills/react/rules/bundle-barrel-imports.md
Normal file
59
.opencode/skills/react/rules/bundle-barrel-imports.md
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
title: Avoid Barrel File Imports
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 200-800ms import cost, slow builds
|
||||||
|
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avoid Barrel File Imports
|
||||||
|
|
||||||
|
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||||
|
|
||||||
|
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||||
|
|
||||||
|
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||||
|
|
||||||
|
**Incorrect (imports entire library):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Check, X, Menu } from 'lucide-react'
|
||||||
|
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||||
|
// Runtime cost: 200-800ms on every cold start
|
||||||
|
|
||||||
|
import { Button, TextField } from '@mui/material'
|
||||||
|
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (imports only what you need):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import Check from 'lucide-react/dist/esm/icons/check'
|
||||||
|
import X from 'lucide-react/dist/esm/icons/x'
|
||||||
|
import Menu from 'lucide-react/dist/esm/icons/menu'
|
||||||
|
// Loads only 3 modules (~2KB vs ~1MB)
|
||||||
|
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import TextField from '@mui/material/TextField'
|
||||||
|
// Loads only what you use
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative (Next.js 13.5+):**
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js - use optimizePackageImports
|
||||||
|
module.exports = {
|
||||||
|
experimental: {
|
||||||
|
optimizePackageImports: ['lucide-react', '@mui/material']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then you can keep the ergonomic barrel imports:
|
||||||
|
import { Check, X, Menu } from 'lucide-react'
|
||||||
|
// Automatically transformed to direct imports at build time
|
||||||
|
```
|
||||||
|
|
||||||
|
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||||
|
|
||||||
|
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||||
|
|
||||||
|
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||||
31
.opencode/skills/react/rules/bundle-conditional.md
Normal file
31
.opencode/skills/react/rules/bundle-conditional.md
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
title: Conditional Module Loading
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: loads large data only when needed
|
||||||
|
tags: bundle, conditional-loading, lazy-loading
|
||||||
|
---
|
||||||
|
|
||||||
|
## Conditional Module Loading
|
||||||
|
|
||||||
|
Load large data or modules only when a feature is activated.
|
||||||
|
|
||||||
|
**Example (lazy-load animation frames):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
|
||||||
|
const [frames, setFrames] = useState<Frame[] | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (enabled && !frames && typeof window !== 'undefined') {
|
||||||
|
import('./animation-frames.js')
|
||||||
|
.then(mod => setFrames(mod.frames))
|
||||||
|
.catch(() => setEnabled(false))
|
||||||
|
}
|
||||||
|
}, [enabled, frames, setEnabled])
|
||||||
|
|
||||||
|
if (!frames) return <Skeleton />
|
||||||
|
return <Canvas frames={frames} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||||
49
.opencode/skills/react/rules/bundle-defer-third-party.md
Normal file
49
.opencode/skills/react/rules/bundle-defer-third-party.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: Defer Non-Critical Third-Party Libraries
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: loads after hydration
|
||||||
|
tags: bundle, third-party, analytics, defer
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer Non-Critical Third-Party Libraries
|
||||||
|
|
||||||
|
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||||
|
|
||||||
|
**Incorrect (blocks initial bundle):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Analytics } from '@vercel/analytics/react'
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<Analytics />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (loads after hydration):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const Analytics = dynamic(
|
||||||
|
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
||||||
|
{ ssr: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<Analytics />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
35
.opencode/skills/react/rules/bundle-dynamic-imports.md
Normal file
35
.opencode/skills/react/rules/bundle-dynamic-imports.md
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
---
|
||||||
|
title: Dynamic Imports for Heavy Components
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: directly affects TTI and LCP
|
||||||
|
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dynamic Imports for Heavy Components
|
||||||
|
|
||||||
|
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||||
|
|
||||||
|
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { MonacoEditor } from './monaco-editor'
|
||||||
|
|
||||||
|
function CodePanel({ code }: { code: string }) {
|
||||||
|
return <MonacoEditor value={code} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (Monaco loads on demand):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const MonacoEditor = dynamic(
|
||||||
|
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
||||||
|
{ ssr: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
function CodePanel({ code }: { code: string }) {
|
||||||
|
return <MonacoEditor value={code} />
|
||||||
|
}
|
||||||
|
```
|
||||||
50
.opencode/skills/react/rules/bundle-preload.md
Normal file
50
.opencode/skills/react/rules/bundle-preload.md
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: Preload Based on User Intent
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces perceived latency
|
||||||
|
tags: bundle, preload, user-intent, hover
|
||||||
|
---
|
||||||
|
|
||||||
|
## Preload Based on User Intent
|
||||||
|
|
||||||
|
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||||
|
|
||||||
|
**Example (preload on hover/focus):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||||
|
const preload = () => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
void import('./monaco-editor')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onMouseEnter={preload}
|
||||||
|
onFocus={preload}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
Open Editor
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example (preload when feature flag is enabled):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FlagsProvider({ children, flags }: Props) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||||
|
void import('./monaco-editor').then(mod => mod.init())
|
||||||
|
}
|
||||||
|
}, [flags.editorEnabled])
|
||||||
|
|
||||||
|
return <FlagsContext.Provider value={flags}>
|
||||||
|
{children}
|
||||||
|
</FlagsContext.Provider>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||||
74
.opencode/skills/react/rules/client-event-listeners.md
Normal file
74
.opencode/skills/react/rules/client-event-listeners.md
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
title: Deduplicate Global Event Listeners
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: single listener for N components
|
||||||
|
tags: client, swr, event-listeners, subscription
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deduplicate Global Event Listeners
|
||||||
|
|
||||||
|
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||||
|
|
||||||
|
**Incorrect (N instances = N listeners):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.metaKey && e.key === key) {
|
||||||
|
callback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', handler)
|
||||||
|
return () => window.removeEventListener('keydown', handler)
|
||||||
|
}, [key, callback])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||||
|
|
||||||
|
**Correct (N instances = 1 listener):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import useSWRSubscription from 'swr/subscription'
|
||||||
|
|
||||||
|
// Module-level Map to track callbacks per key
|
||||||
|
const keyCallbacks = new Map<string, Set<() => void>>()
|
||||||
|
|
||||||
|
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||||
|
// Register this callback in the Map
|
||||||
|
useEffect(() => {
|
||||||
|
if (!keyCallbacks.has(key)) {
|
||||||
|
keyCallbacks.set(key, new Set())
|
||||||
|
}
|
||||||
|
keyCallbacks.get(key)!.add(callback)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
const set = keyCallbacks.get(key)
|
||||||
|
if (set) {
|
||||||
|
set.delete(callback)
|
||||||
|
if (set.size === 0) {
|
||||||
|
keyCallbacks.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [key, callback])
|
||||||
|
|
||||||
|
useSWRSubscription('global-keydown', () => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||||
|
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', handler)
|
||||||
|
return () => window.removeEventListener('keydown', handler)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function Profile() {
|
||||||
|
// Multiple shortcuts will share the same listener
|
||||||
|
useKeyboardShortcut('p', () => { /* ... */ })
|
||||||
|
useKeyboardShortcut('k', () => { /* ... */ })
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
71
.opencode/skills/react/rules/client-localstorage-schema.md
Normal file
71
.opencode/skills/react/rules/client-localstorage-schema.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
---
|
||||||
|
title: Version and Minimize localStorage Data
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: prevents schema conflicts, reduces storage size
|
||||||
|
tags: client, localStorage, storage, versioning, data-minimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Version and Minimize localStorage Data
|
||||||
|
|
||||||
|
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// No version, stores everything, no error handling
|
||||||
|
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
|
||||||
|
const data = localStorage.getItem('userConfig')
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const VERSION = 'v2'
|
||||||
|
|
||||||
|
function saveConfig(config: { theme: string; language: string }) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
|
||||||
|
} catch {
|
||||||
|
// Throws in incognito/private browsing, quota exceeded, or disabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadConfig() {
|
||||||
|
try {
|
||||||
|
const data = localStorage.getItem(`userConfig:${VERSION}`)
|
||||||
|
return data ? JSON.parse(data) : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migration from v1 to v2
|
||||||
|
function migrate() {
|
||||||
|
try {
|
||||||
|
const v1 = localStorage.getItem('userConfig:v1')
|
||||||
|
if (v1) {
|
||||||
|
const old = JSON.parse(v1)
|
||||||
|
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
|
||||||
|
localStorage.removeItem('userConfig:v1')
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Store minimal fields from server responses:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// User object has 20+ fields, only store what UI needs
|
||||||
|
function cachePrefs(user: FullUser) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem('prefs:v1', JSON.stringify({
|
||||||
|
theme: user.preferences.theme,
|
||||||
|
notifications: user.preferences.notifications
|
||||||
|
}))
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
|
||||||
|
|
||||||
|
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
---
|
||||||
|
title: Use Passive Event Listeners for Scrolling Performance
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: eliminates scroll delay caused by event listeners
|
||||||
|
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Passive Event Listeners for Scrolling Performance
|
||||||
|
|
||||||
|
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
useEffect(() => {
|
||||||
|
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||||
|
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||||
|
|
||||||
|
document.addEventListener('touchstart', handleTouch)
|
||||||
|
document.addEventListener('wheel', handleWheel)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('touchstart', handleTouch)
|
||||||
|
document.removeEventListener('wheel', handleWheel)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
useEffect(() => {
|
||||||
|
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||||
|
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||||
|
|
||||||
|
document.addEventListener('touchstart', handleTouch, { passive: true })
|
||||||
|
document.addEventListener('wheel', handleWheel, { passive: true })
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('touchstart', handleTouch)
|
||||||
|
document.removeEventListener('wheel', handleWheel)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
```
|
||||||
|
|
||||||
|
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||||
|
|
||||||
|
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||||
56
.opencode/skills/react/rules/client-swr-dedup.md
Normal file
56
.opencode/skills/react/rules/client-swr-dedup.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
---
|
||||||
|
title: Use SWR for Automatic Deduplication
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: automatic deduplication
|
||||||
|
tags: client, swr, deduplication, data-fetching
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use SWR for Automatic Deduplication
|
||||||
|
|
||||||
|
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||||
|
|
||||||
|
**Incorrect (no deduplication, each instance fetches):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function UserList() {
|
||||||
|
const [users, setUsers] = useState([])
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/users')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(setUsers)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (multiple instances share one request):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import useSWR from 'swr'
|
||||||
|
|
||||||
|
function UserList() {
|
||||||
|
const { data: users } = useSWR('/api/users', fetcher)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**For immutable data:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useImmutableSWR } from '@/lib/swr'
|
||||||
|
|
||||||
|
function StaticContent() {
|
||||||
|
const { data } = useImmutableSWR('/api/config', fetcher)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**For mutations:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useSWRMutation } from 'swr/mutation'
|
||||||
|
|
||||||
|
function UpdateButton() {
|
||||||
|
const { trigger } = useSWRMutation('/api/user', updateUser)
|
||||||
|
return <button onClick={() => trigger()}>Update</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||||
82
.opencode/skills/react/rules/js-batch-dom-css.md
Normal file
82
.opencode/skills/react/rules/js-batch-dom-css.md
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Batch DOM CSS Changes
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces reflows/repaints
|
||||||
|
tags: javascript, dom, css, performance, reflow
|
||||||
|
---
|
||||||
|
|
||||||
|
## Batch DOM CSS Changes
|
||||||
|
|
||||||
|
Avoid changing styles one property at a time. Group multiple CSS changes together via classes or `cssText` to minimize browser reflows.
|
||||||
|
|
||||||
|
**Incorrect (multiple reflows):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
// Each line triggers a reflow
|
||||||
|
element.style.width = '100px'
|
||||||
|
element.style.height = '200px'
|
||||||
|
element.style.backgroundColor = 'blue'
|
||||||
|
element.style.border = '1px solid black'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (add class - single reflow):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// CSS file
|
||||||
|
.highlighted-box {
|
||||||
|
width: 100px;
|
||||||
|
height: 200px;
|
||||||
|
background-color: blue;
|
||||||
|
border: 1px solid black;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JavaScript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
element.classList.add('highlighted-box')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (change cssText - single reflow):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
element.style.cssText = `
|
||||||
|
width: 100px;
|
||||||
|
height: 200px;
|
||||||
|
background-color: blue;
|
||||||
|
border: 1px solid black;
|
||||||
|
`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**React example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Incorrect: changing styles one by one
|
||||||
|
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (ref.current && isHighlighted) {
|
||||||
|
ref.current.style.width = '100px'
|
||||||
|
ref.current.style.height = '200px'
|
||||||
|
ref.current.style.backgroundColor = 'blue'
|
||||||
|
}
|
||||||
|
}, [isHighlighted])
|
||||||
|
|
||||||
|
return <div ref={ref}>Content</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct: toggle class
|
||||||
|
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
||||||
|
Content
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Prefer CSS classes over inline styles when possible. Classes are cached by the browser and provide better separation of concerns.
|
||||||
80
.opencode/skills/react/rules/js-cache-function-results.md
Normal file
80
.opencode/skills/react/rules/js-cache-function-results.md
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
title: Cache Repeated Function Calls
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoid redundant computation
|
||||||
|
tags: javascript, cache, memoization, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Repeated Function Calls
|
||||||
|
|
||||||
|
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||||
|
|
||||||
|
**Incorrect (redundant computation):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function ProjectList({ projects }: { projects: Project[] }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{projects.map(project => {
|
||||||
|
// slugify() called 100+ times for same project names
|
||||||
|
const slug = slugify(project.name)
|
||||||
|
|
||||||
|
return <ProjectCard key={project.id} slug={slug} />
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (cached results):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Module-level cache
|
||||||
|
const slugifyCache = new Map<string, string>()
|
||||||
|
|
||||||
|
function cachedSlugify(text: string): string {
|
||||||
|
if (slugifyCache.has(text)) {
|
||||||
|
return slugifyCache.get(text)!
|
||||||
|
}
|
||||||
|
const result = slugify(text)
|
||||||
|
slugifyCache.set(text, result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectList({ projects }: { projects: Project[] }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{projects.map(project => {
|
||||||
|
// Computed only once per unique project name
|
||||||
|
const slug = cachedSlugify(project.name)
|
||||||
|
|
||||||
|
return <ProjectCard key={project.id} slug={slug} />
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Simpler pattern for single-value functions:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
let isLoggedInCache: boolean | null = null
|
||||||
|
|
||||||
|
function isLoggedIn(): boolean {
|
||||||
|
if (isLoggedInCache !== null) {
|
||||||
|
return isLoggedInCache
|
||||||
|
}
|
||||||
|
|
||||||
|
isLoggedInCache = document.cookie.includes('auth=')
|
||||||
|
return isLoggedInCache
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear cache when auth changes
|
||||||
|
function onAuthChange() {
|
||||||
|
isLoggedInCache = null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||||
|
|
||||||
|
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||||
28
.opencode/skills/react/rules/js-cache-property-access.md
Normal file
28
.opencode/skills/react/rules/js-cache-property-access.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Cache Property Access in Loops
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces lookups
|
||||||
|
tags: javascript, loops, optimization, caching
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Property Access in Loops
|
||||||
|
|
||||||
|
Cache object property lookups in hot paths.
|
||||||
|
|
||||||
|
**Incorrect (3 lookups × N iterations):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
process(obj.config.settings.value)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 lookup total):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const value = obj.config.settings.value
|
||||||
|
const len = arr.length
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
process(value)
|
||||||
|
}
|
||||||
|
```
|
||||||
70
.opencode/skills/react/rules/js-cache-storage.md
Normal file
70
.opencode/skills/react/rules/js-cache-storage.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
---
|
||||||
|
title: Cache Storage API Calls
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces expensive I/O
|
||||||
|
tags: javascript, localStorage, storage, caching, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Storage API Calls
|
||||||
|
|
||||||
|
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||||
|
|
||||||
|
**Incorrect (reads storage on every call):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getTheme() {
|
||||||
|
return localStorage.getItem('theme') ?? 'light'
|
||||||
|
}
|
||||||
|
// Called 10 times = 10 storage reads
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (Map cache):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const storageCache = new Map<string, string | null>()
|
||||||
|
|
||||||
|
function getLocalStorage(key: string) {
|
||||||
|
if (!storageCache.has(key)) {
|
||||||
|
storageCache.set(key, localStorage.getItem(key))
|
||||||
|
}
|
||||||
|
return storageCache.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLocalStorage(key: string, value: string) {
|
||||||
|
localStorage.setItem(key, value)
|
||||||
|
storageCache.set(key, value) // keep cache in sync
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||||
|
|
||||||
|
**Cookie caching:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
let cookieCache: Record<string, string> | null = null
|
||||||
|
|
||||||
|
function getCookie(name: string) {
|
||||||
|
if (!cookieCache) {
|
||||||
|
cookieCache = Object.fromEntries(
|
||||||
|
document.cookie.split('; ').map(c => c.split('='))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return cookieCache[name]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important (invalidate on external changes):**
|
||||||
|
|
||||||
|
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
window.addEventListener('storage', (e) => {
|
||||||
|
if (e.key) storageCache.delete(e.key)
|
||||||
|
})
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (document.visibilityState === 'visible') {
|
||||||
|
storageCache.clear()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
32
.opencode/skills/react/rules/js-combine-iterations.md
Normal file
32
.opencode/skills/react/rules/js-combine-iterations.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
title: Combine Multiple Array Iterations
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces iterations
|
||||||
|
tags: javascript, arrays, loops, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Combine Multiple Array Iterations
|
||||||
|
|
||||||
|
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||||
|
|
||||||
|
**Incorrect (3 iterations):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const admins = users.filter(u => u.isAdmin)
|
||||||
|
const testers = users.filter(u => u.isTester)
|
||||||
|
const inactive = users.filter(u => !u.isActive)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 iteration):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const admins: User[] = []
|
||||||
|
const testers: User[] = []
|
||||||
|
const inactive: User[] = []
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (user.isAdmin) admins.push(user)
|
||||||
|
if (user.isTester) testers.push(user)
|
||||||
|
if (!user.isActive) inactive.push(user)
|
||||||
|
}
|
||||||
|
```
|
||||||
50
.opencode/skills/react/rules/js-early-exit.md
Normal file
50
.opencode/skills/react/rules/js-early-exit.md
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: Early Return from Functions
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: avoids unnecessary computation
|
||||||
|
tags: javascript, functions, optimization, early-return
|
||||||
|
---
|
||||||
|
|
||||||
|
## Early Return from Functions
|
||||||
|
|
||||||
|
Return early when result is determined to skip unnecessary processing.
|
||||||
|
|
||||||
|
**Incorrect (processes all items even after finding answer):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function validateUsers(users: User[]) {
|
||||||
|
let hasError = false
|
||||||
|
let errorMessage = ''
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (!user.email) {
|
||||||
|
hasError = true
|
||||||
|
errorMessage = 'Email required'
|
||||||
|
}
|
||||||
|
if (!user.name) {
|
||||||
|
hasError = true
|
||||||
|
errorMessage = 'Name required'
|
||||||
|
}
|
||||||
|
// Continues checking all users even after error found
|
||||||
|
}
|
||||||
|
|
||||||
|
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (returns immediately on first error):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function validateUsers(users: User[]) {
|
||||||
|
for (const user of users) {
|
||||||
|
if (!user.email) {
|
||||||
|
return { valid: false, error: 'Email required' }
|
||||||
|
}
|
||||||
|
if (!user.name) {
|
||||||
|
return { valid: false, error: 'Name required' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true }
|
||||||
|
}
|
||||||
|
```
|
||||||
45
.opencode/skills/react/rules/js-hoist-regexp.md
Normal file
45
.opencode/skills/react/rules/js-hoist-regexp.md
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
title: Hoist RegExp Creation
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: avoids recreation
|
||||||
|
tags: javascript, regexp, optimization, memoization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hoist RegExp Creation
|
||||||
|
|
||||||
|
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||||
|
|
||||||
|
**Incorrect (new RegExp every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Highlighter({ text, query }: Props) {
|
||||||
|
const regex = new RegExp(`(${query})`, 'gi')
|
||||||
|
const parts = text.split(regex)
|
||||||
|
return <>{parts.map((part, i) => ...)}</>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (memoize or hoist):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
|
||||||
|
function Highlighter({ text, query }: Props) {
|
||||||
|
const regex = useMemo(
|
||||||
|
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||||
|
[query]
|
||||||
|
)
|
||||||
|
const parts = text.split(regex)
|
||||||
|
return <>{parts.map((part, i) => ...)}</>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warning (global regex has mutable state):**
|
||||||
|
|
||||||
|
Global regex (`/g`) has mutable `lastIndex` state:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const regex = /foo/g
|
||||||
|
regex.test('foo') // true, lastIndex = 3
|
||||||
|
regex.test('foo') // false, lastIndex = 0
|
||||||
|
```
|
||||||
37
.opencode/skills/react/rules/js-index-maps.md
Normal file
37
.opencode/skills/react/rules/js-index-maps.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
title: Build Index Maps for Repeated Lookups
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: 1M ops to 2K ops
|
||||||
|
tags: javascript, map, indexing, optimization, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Build Index Maps for Repeated Lookups
|
||||||
|
|
||||||
|
Multiple `.find()` calls by the same key should use a Map.
|
||||||
|
|
||||||
|
**Incorrect (O(n) per lookup):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function processOrders(orders: Order[], users: User[]) {
|
||||||
|
return orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
user: users.find(u => u.id === order.userId)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (O(1) per lookup):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function processOrders(orders: Order[], users: User[]) {
|
||||||
|
const userById = new Map(users.map(u => [u.id, u]))
|
||||||
|
|
||||||
|
return orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
user: userById.get(order.userId)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Build map once (O(n)), then all lookups are O(1).
|
||||||
|
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user