Compare commits

..

35 Commits

Author SHA1 Message Date
lucasacchi
1dc2f658a0 Update README.md
chores
2026-04-07 11:30:19 +02:00
lucasacchi
a3a641595d Update README.md
added link to 'mockupAWS - Backend Profiler & Cost Estimator'
2026-04-07 11:29:35 +02:00
Luca Sacchi Ricciardi
c2c922c1b7 docs: add demo link to README
Add link to live demo at https://logwhispererai.lab.home.lucasacchi.net/
2026-04-06 12:20:14 +02:00
Luca Sacchi Ricciardi
894073644f fix: disable HMR in production to fix WebSocket error behind reverse proxy
- Disable HMR when NODE_ENV=production to prevent WebSocket binding errors
- HMR was trying to bind to external IP:443 which is not available in Docker
- App now works correctly behind HTTPS reverse proxy
2026-04-03 18:55:21 +02:00
Luca Sacchi Ricciardi
26879acba4 feat: add production configuration with environment variables
- Add .env file for production deployment with reverse proxy
- Add docker-compose.prod.yml for production profile
- Add docker-compose.override.yml for local development
- Update docker-compose.yml with all configurable variables
- Update frontend to use VITE_* environment variables
- Update backend to support CORS_ORIGINS and WEBHOOK_BASE_URL
- Add vite.config.ts allowedHosts for reverse proxy
- Add documentation for docker-compose and reverse proxy setup

All URLs are now configurable via environment variables:
- VITE_API_URL: Backend API endpoint
- VITE_WEBHOOK_BASE_URL: Webhook base URL
- VITE_INSTALL_SCRIPT_URL: Install script URL
- VITE_APP_URL: Frontend URL
- CORS_ORIGINS: Allowed CORS origins
- WEBHOOK_BASE_URL: Backend webhook base URL
2026-04-03 18:49:53 +02:00
Luca Sacchi Ricciardi
92217897ca fix: standardize project name to LogWhispererAI (no space)
- Replace all occurrences of 'LogWhisperer AI' with 'LogWhispererAI'
- Fix 47 instances across 30 files including:
  - Documentation (README, PRD, specs, docs)
  - Frontend components (Footer, Navbar, Hero, etc.)
  - Backend files (Dockerfile, server.js)
  - Workflow files (n8n, bash scripts)
  - Configuration files (AGENTS.md, LICENSE)

Ensures consistent branding across the entire codebase.
2026-04-03 17:07:35 +02:00
Luca Sacchi Ricciardi
8eb7dfb00e feat: add fake-backend mock API server for frontend development
Create mock backend to simulate AI responses for UI development:

Backend Implementation:
- tools/fake-backend/server.js: Express server with CORS
- POST /api/analyze: Accepts log, returns mock AI analysis with 1.5s delay
- GET /health: Health check endpoint
- Pattern matching for different log types (PostgreSQL, Nginx, Node.js, Disk)
- Error handling: 400 for empty payload, 500 for server errors
- Mock responses for common errors (OOM, 502, connection refused, disk full)

Container Setup:
- Dockerfile: Node.js 20 Alpine container
- docker-compose.yml: Added fake-backend service on port 3000
- Health checks for both frontend and backend services
- Environment variable VITE_API_URL for frontend

Frontend Integration:
- InteractiveDemo.tsx: Replaced static data with real fetch() calls
- API_URL configurable via env var (default: http://localhost:3000)
- Error handling with user-friendly messages
- Shows backend URL in demo section
- Maintains loading states and UI feedback

Documentation:
- docs/tools_fake_backend.md: Complete usage guide
- README.md: Updated with tools/fake-backend structure and usage

Development Workflow:
1. docker compose up -d (starts both frontend and backend)
2. Frontend calls http://fake-backend:3000/api/analyze
3. Backend returns realistic mock responses
4. No OpenRouter API costs during development

Safety First:
- No real API calls during development
- Isolated mock logic in dedicated tool
- Easy switch to real backend by changing URL
- CORS enabled only for development

Refs: Sprint 4 preparation, API development workflow
2026-04-03 16:57:14 +02:00
Luca Sacchi Ricciardi
eb24b86308 feat: add Footer and OnboardingWizard components - Sprint 3 Complete
Complete Sprint 3 Landing Page development with final 20%:

Footer Component:
- 4-column layout: Brand, Useful Links, Legal, Newsletter
- SVG social icons (GitHub, Twitter, LinkedIn, YouTube)
- Working newsletter form with success feedback
- Dark theme design (slate-900) with proper contrast
- Copyright and attribution footer

OnboardingWizard Component:
- 3-step wizard with progress indicator
- Step 1: Welcome with service explanation
- Step 2: Webhook generation (crypto.randomUUID)
- Step 3: Setup instructions with curl command
- UUID generation and clipboard copy functionality
- Mock implementation (no backend API calls)

Accessibility Features:
- aria-live=polite on wizard container
- aria-current=step for progress indication
- Focus management with useRef/useEffect
- Keyboard navigation support
- Proper ARIA labels on interactive elements

Integration:
- Added to components/index.ts exports
- Integrated in App.tsx after InteractiveDemo
- CTAs scroll to #onboarding section
- Footer placed at page bottom

Build Verification:
- TypeScript compilation: ✓ 0 errors
- CSS bundle: 34KB (gzipped 7KB)
- JS bundle: 238KB (gzipped 72KB)

Sprint 3 Status: 100% Complete 
Landing Page now includes:
- Hero, Problem/Solution, HowItWorks, Demo, Onboarding, Footer

Refs: docs/frontend_landing_plan.md
2026-04-03 16:43:23 +02:00
Luca Sacchi Ricciardi
462a5a9383 docs: update README with real project status
Reflect actual project progress in README:
- Sprint 2: COMPLETED (AI Pipeline + Telegram alerting)
- Sprint 3: IN PROGRESS (~80% - Landing Page development)
- Updated MVP features status with file references
- Changed sprint badge from 1 to 2 completed

Previous README showed Sprint 2/3 as 'in planning' when they
were actually completed/in progress. Now accurately reflects:
- Log Ingestion: DONE (scripts/)
- AI Processing: DONE (workflows/ with OpenRouter)
- Telegram Alerting: DONE (docs/telegram_setup.md)
- Landing Page: IN PROGRESS (frontend/ 80% complete)
2026-04-03 16:34:09 +02:00
Luca Sacchi Ricciardi
c131343321 docs: clarify Interactive Demo uses mock data, not real OpenRouter
Update documentation to reflect demo simulation status:

README.md: Add note explaining demo uses static mock data
CHANGELOG.md: Add Interactive Demo entry marked as Mock
roadmap_ideas.md: Update status to in-evaluation with priority note

Prevents user confusion about AI capabilities in demo section.

Refs: Sprint 3, demo clarification
2026-04-03 16:30:10 +02:00
Luca Sacchi Ricciardi
f3e65ee36f docs: add roadmap ideas document for future development
Create comprehensive living document to track improvement suggestions
and potential new features for LogWhisperer AI roadmap.

Structure includes:
- Status legend (💡🤔📅🚧)
- Categorized by priority and area:
  * Core Features (Backend, AI)
  * UX/UI & Frontend
  * Security & Compliance
  * Integrations (Slack, Discord, etc.)
  * Monitoring & Analytics
  * Developer Experience
  * Internationalization
  * Monetization
- Completed sprints tracking
- Rejected ideas section with rationale
- Notes on performance, costs, scalability
- Contribution guidelines

Serves as central hub for team to propose, evaluate,
and track feature ideas before they enter formal roadmap.

Refs: Sprint 3 planning, team brainstorming
2026-04-03 16:26:45 +02:00
Luca Sacchi Ricciardi
9eb1e0ddf5 fix: implement scroll to demo section on 'Guarda la Demo' button click
The 'Guarda la Demo' (Watch Demo) button in Hero section was not working.
Now it smoothly scrolls to the InteractiveDemo section.

Changes:
- Added id='demo-interattiva' to InteractiveDemo section
- Implemented handleSecondaryCta with document.getElementById
- Used scrollIntoView with smooth behavior for better UX

Refs: User feedback - button was not functional
2026-04-03 16:22:32 +02:00
Luca Sacchi Ricciardi
04db2b30be feat: add InteractiveDemo section with mock AI analysis
Create interactive demo component showcasing AI log analysis:

Layout:
- Two-column responsive grid (side-by-side desktop, stacked mobile)
- Left panel: Terminal-style input with log selection
- Right panel: AI analysis output with results

Terminal Panel (Left):
- Dark terminal design (bg-slate-900) with header
- 3 preset log buttons: PostgreSQL OOM, Nginx 502, Node.js Exception
- Terminal content area with monospace font
- Blinking cursor animation
- Log content display with syntax highlighting

Analysis Panel (Right):
- Initial state with guidance message
- Loading animation: 'Analisi in corso...' with 1.5s delay
- Result display with title, description, command
- Command box with copy button and feedback
- Safety badge and additional notes

React Logic:
- useState for selection, loading, analysis states
- Simulated 1.5s delay with setTimeout
- Static mock data (no API calls)
- Copy to clipboard functionality with visual feedback

Accessibility:
- aria-live=polite on output panel for screen readers
- aria-atomic=true for complete announcements
- aria-pressed on selection buttons
- aria-label on interactive elements
- Icons hidden from screen readers

TypeScript:
- LogAnalysis interface defined
- Proper type safety throughout
- Build passes without errors

Integration:
- Added to components/index.ts exports
- Integrated in App.tsx after HowItWorks section

Refs: Giorno 4 - Sprint 3 Landing Page development
2026-04-03 16:19:23 +02:00
Luca Sacchi Ricciardi
644622f21c fix: remove conflicting CSS legacy styles causing white-on-white text
Critical bug fix (P0): Text appearing white-on-white and unreadable.

Root Cause:
- CSS legacy styles in index.css were setting global colors via :root variables
- color-scheme: light dark was interfering with Tailwind classes
- Global color: var(--text) and background: var(--bg) were overriding Tailwind
- Dark mode media query was applying even when Tailwind expected light mode
- Variables like --text-h were referenced but not properly initialized

Fix:
- Removed all legacy CSS variable definitions
- Removed color-scheme declaration that interfered with Tailwind
- Removed global color/background declarations
- Simplified index.css to only import Tailwind and set minimal base styles
- Let Tailwind utility classes handle all colors completely

Result:
- Text now renders with correct Tailwind colors (text-slate-900, text-indigo-700, etc.)
- Badge with 'Sprint 2 Completato' now visible with indigo background
- Headline 'Il DevOps tascabile...' now renders in dark slate
- Build successful: 28KB CSS bundle with all utilities

Safety First:
- Verified build passes
- No breaking changes to component structure
- Tailwind classes now have full control over styling
- Minimal base styles preserved for font-smoothing

Refs: Tailwind v4 CSS-first configuration
2026-04-03 16:12:07 +02:00
Luca Sacchi Ricciardi
135782e54b refactor: improve layout with consistent containers and spacing
Apply UI refactoring following design best practices:

Layout Improvements:
- Standardize all sections to use max-w-7xl mx-auto px-4 container
- Increase vertical spacing: py-24 lg:py-32 for better whitespace
- Move padding-x from section to inner container for consistency
- Improve visual hierarchy with generous breathing room

Components Updated:
- Navbar: Consistent container padding structure
- Hero: max-w-5xl → max-w-7xl, increased py-16 → py-24
- ProblemSolution: max-w-6xl → max-w-7xl, py-16 → py-24
- HowItWorks: max-w-6xl → max-w-7xl, py-16 → py-24

Design Principles Applied:
- Consistent max-width containers (max-w-7xl)
- Generous whitespace between sections (py-24/32)
- Mobile-first responsive padding (px-4 sm:px-6 lg:px-8)
- Better readability with ample vertical spacing

Safety First:
- Verified Tailwind classes compile correctly
- Layout remains responsive across breakpoints
- No breaking changes to component logic
- Incremental improvements following 'little often'

Refs: docs/frontend_landing_plan.md
2026-04-03 16:08:32 +02:00
Luca Sacchi Ricciardi
6b5261f760 fix: add Tailwind v4 import directive to index.css
Critical bug fix (P0): Tailwind CSS classes were not being compiled.

Root Cause:
- Tailwind v4 requires explicit @import tailwindcss in CSS file
- File was missing this directive, causing all utility classes to be ignored
- CSS bundle was only 4KB instead of expected 30KB+

Fix:
- Added @import tailwindcss; at the top of src/index.css
- Verified build now generates 30KB+ CSS bundle with all utility classes
- Confirmed classes like text-3xl, bg-indigo-600, max-w-7xl are present

Safety First:
- Build passes successfully
- No breaking changes to existing styles
- Incremental fix before UI refactoring

Refs: Tailwind v4 migration guide
2026-04-03 15:43:40 +02:00
Luca Sacchi Ricciardi
976dd95dc8 feat: add Docker development environment for frontend
Create containerized development setup for safe and consistent frontend development:

Docker Configuration:
- docker-compose.yml: Root-level orchestration with frontend service
- frontend/Dockerfile.dev: Node.js 20 Alpine optimized for dev
- Volume mounts for Hot Module Replacement (HMR)
- Named volume for node_modules to avoid conflicts
- Health check to verify service availability
- Environment variables for file watching (CHOKIDAR_USEPOLLING)

Vite Configuration Update:
- vite.config.ts: Add server config for Docker compatibility
- host: '0.0.0.0' to accept external connections
- usePolling: true for file watching in container
- port: 5173 explicitly configured

Documentation:
- README.md: Add Docker development procedure section
- Document docker compose up -d workflow
- Explain HMR and hot-reload capabilities
- List advantages of Docker-based development

Usage:
  docker compose up -d        # Start development server
  docker compose logs -f      # View logs
  docker compose down         # Stop container

Access: http://localhost:5173

Safety First:
- Isolated environment prevents system conflicts
- Reproducible setup across different machines
- No host Node.js installation required
- Easy team onboarding

Refs: Docker best practices for Node.js development
2026-04-03 14:47:36 +02:00
Luca Sacchi Ricciardi
84338ea861 feat: add ProblemSolution and HowItWorks sections with accessible animations
Create two new landing page sections following Day 3 objectives:

ProblemSolution.tsx:
- Before/After comparison layout (2-column grid)
- Terminal simulation showing cryptic PostgreSQL logs
- Telegram message simulation with clear solution
- Pain points vs benefits comparison lists
- Arrow connector between problem and solution
- Final CTA button

HowItWorks.tsx:
- 3-step card layout (Monitor, Analyze, Notify)
- StepCard sub-component with icons from Lucide React
- Server, Brain, MessageSquare icons for each step
- Detailed bullet points for each step
- Connector lines between cards (desktop)
- CSS fade-up animations with stagger effect
- Final CTA box with button

Accessibility Features:
- Respects prefers-reduced-motion media query
- Disables all animations if user prefers reduced motion
- Proper focus rings on interactive elements
- Aria-labels and aria-hidden on decorative icons
- Semantic HTML structure

Animation Implementation:
- Pure CSS animations (no Framer Motion - parsimony)
- @keyframes fadeUp: 600ms ease-out
- Stagger delays: 0.1s, 0.2s, 0.3s between cards
- Smooth hover transitions on cards
- Transform scale on icon hover

Responsive Design:
- Mobile: single column layout
- Tablet: 2-column grid
- Desktop: 3-column grid with connector lines
- Adaptive spacing and font sizes

Integration:
- Added exports to components/index.ts
- Integrated into App.tsx below Hero section
- Consistent styling with existing components

Build Verification:
- TypeScript compilation: ✓ 0 errors
- Vite build: ✓ Success
- Bundle size: 208KB (65KB gzipped)
- All components render correctly

Icons Installed:
- lucide-react for consistent iconography
- Terminal, AlertCircle, CheckCircle, ArrowRight
- Server, Brain, MessageSquare

Refs: .opencode/skills/ui-ux-master (animation best practices)
2026-04-03 14:42:02 +02:00
Luca Sacchi Ricciardi
a22e4bf7b5 feat: add Navbar and Hero components with Tailwind styling
Create landing page structure following 'Little Often' principle:

Components Created:
- Navbar.tsx: Logo + CTA button with sticky positioning
- Hero.tsx: Headline, sub-headline, dual CTAs, trust indicators, stats
- components/index.ts: Centralized exports

Design Features:
- Mobile-first responsive design (sm:, lg: breakpoints)
- WCAG AA compliant contrast ratios (4.5:1+)
- Accessible focus rings and aria-labels
- Modern color palette (indigo primary, slate neutrals)
- Smooth gradients and shadows

Layout Structure:
frontend/src/
├── components/
│   ├── layout/
│   │   └── Navbar.tsx
│   ├── sections/
│   │   └── Hero.tsx
│   └── index.ts
├── App.tsx: Clean integration of Navbar + Hero

Fixes Applied:
- Install @tailwindcss/postcss for Tailwind v4 compatibility
- Update postcss.config.js with new plugin
- Remove @tailwind directives from index.css (v4 style)

Build Verification:
 TypeScript compilation successful
 Tailwind CSS processing successful
 Production build completed (dist/ folder)

Content:
- Headline: 'Il DevOps tascabile che traduce i crash...'
- Sub-headline: Explains monitoring + AI + Telegram flow
- Primary CTA: 'Ottieni il tuo Webhook URL'
- Secondary CTA: 'Guarda la Demo'
- Stats: <5s response, 300+ models, €0.15/month

Refs: docs/frontend_landing_plan.md, .opencode/skills/frontend-ui-ux/
2026-04-03 14:26:16 +02:00
Luca Sacchi Ricciardi
c7b86de3fb feat: setup React + Vite + TypeScript frontend with Tailwind CSS
Initialize frontend infrastructure for Sprint 3 Landing Page:

Infrastructure Setup:
- Create React + Vite + TypeScript project in frontend/ directory
- Install Tailwind CSS, PostCSS, Autoprefixer dependencies
- Generate tailwind.config.js with content paths
- Generate postcss.config.js with plugins configuration
- Add Tailwind directives (@tailwind base/components/utilities) to src/index.css
- Update root .gitignore to exclude frontend/node_modules and build artifacts

Documentation Updates:
- Add CHANGELOG.md entry for Sprint 3 Landing Page development start
- Update README.md with frontend development instructions
- Add Node.js and npm prerequisites
- Document npm commands: install, dev, build, preview

Project Structure:
├── frontend/
│   ├── src/
│   │   ├── App.tsx
│   │   ├── main.tsx
│   │   ├── index.css (with Tailwind)
│   │   └── assets/
│   ├── index.html
│   ├── package.json
│   ├── tailwind.config.js
│   ├── postcss.config.js
│   └── vite.config.ts

Safety First:
- Verified directory doesn't exist before creation
- Checked all configuration files are valid
- Excluded node_modules from git
- No project code modified, only new frontend directory added

Refs: docs/frontend_landing_plan.md
Next: Start developing landing page components
2026-04-03 13:20:48 +02:00
Luca Sacchi Ricciardi
aa489c7eb8 docs: add comprehensive frontend landing page plan and download design skills
Add detailed landing page development plan in docs/frontend_landing_plan.md:
- Complete landing page structure (Hero, Problem/Solution, Features, Demo, CTA)
- Design guidelines from downloaded skills (typography, color, motion, composition)
- Security considerations (XSS prevention, input sanitization, CSP)
- Performance targets (LCP <2.5s, bundle <150KB, Lighthouse >90)
- Responsiveness and accessibility requirements (WCAG 2.1 AA)
- Success KPIs and monitoring setup
- 3-week development timeline with daily tasks
- Definition of Done checklist

Download 10+ frontend/UI/UX skills via universal-skills-manager:
- frontend-ui-ux: UI/UX design without mockups
- frontend-design-guidelines: Production-grade interface guidelines
- frontend-developer: React best practices (40+ rules)
- frontend-engineer: Next.js 14 App Router patterns
- ui-ux-master: Comprehensive design systems and accessibility
- ui-ux-systems-designer: Information architecture and interaction
- ui-ux-design-user-experience: Platform-specific guidelines
- Plus additional reference materials and validation scripts

Configure universal-skills MCP with SkillsMP API key for curated skill access.

Safety first: All skills validated before installation, no project code modified.

Refs: Universal Skills Manager (github:jacob-bd/universal-skills-manager)
Next: Begin Sprint 3 landing page development
2026-04-03 13:13:59 +02:00
Luca Sacchi Ricciardi
3d24dfdeaf feat: complete Sprint 2 with Telegram notifications integration
Add Telegram Bot notification node to n8n workflow:

New Features:
- Telegram notification node for critical severity logs
- Italian message template with emoji and MarkdownV2 formatting
- Smart routing: Telegram only for critical logs
- Error handling: continueOnFail prevents workflow interruption
- Environment-based configuration (TELEGRAM_CHAT_ID)

Message Template Includes:
- 🚨 Alert header with severity
- 📍 Server hostname identification
- 📝 AI-generated problem summary
- 💡 Suggested bash command in code block
- ⚠️ Confirmation required flag
- 📝 Additional notes from AI
- 📊 AI processing status
- 🤖 Model used (openai/gpt-4o-mini)
-  Localized Italian timestamp

Workflow Flow:
Webhook → HMAC → Validation → PostgreSQL → OpenRouter → Critical? → Telegram → Response
                                                      ↓ FALSE
                                               Success Response

Configuration Required:
1. Create Telegram Bot via @BotFather
2. Get TELEGRAM_BOT_TOKEN
3. Get TELEGRAM_CHAT_ID via @userinfobot
4. Configure credentials in n8n UI
5. Set TELEGRAM_CHAT_ID environment variable

Documentation:
- docs/telegram_setup.md: Setup instructions
- .env.example: Environment variables template
- .gitignore: Protect sensitive telegram_setup.md
- docs/prd.md: Updated Sprint 2 completion status

Sprint 2 Complete:
 Secure log ingestion (bash)
 n8n webhook workflow
 OpenRouter AI integration
 PostgreSQL storage
 HMAC authentication
 Telegram notifications

Refs: docs/specs/ai_pipeline.md, docs/specs/bash_ingestion_secure.md
2026-04-02 19:47:57 +02:00
Luca Sacchi Ricciardi
5aab19626f feat: implement OpenRouter AI integration in n8n workflow
Add 'Call OpenRouter' node to LogWhisperer_Ingest workflow:

New Node Features:
- Model: openai/gpt-4o-mini via OpenRouter API
- System prompt with Metodo Sacchi (Safety First, Little Often, Double Check)
- Timeout: 10 seconds with AbortController
- Log truncation: max 2000 characters
- Required headers: Authorization, HTTP-Referer, X-Title
- Error handling with graceful fallback response
- Output: JSON with ai_analysis, ai_status, ai_timestamp, ai_model

Workflow Flow:
Webhook → HMAC Validation → Data Validation → Store Log → Call OpenRouter → Critical Severity Check → Response

Test Suite (workflows/test_openrouter.js):
- 10 comprehensive tests covering:
  - Input/output structure validation
  - Log truncation logic
  - OpenRouter API payload format
  - Required HTTP headers
  - AI response structure
  - Fallback error handling
  - Timeout configuration
  - Dangerous command patterns
  - System Prompt Metodo Sacchi validation
  - Workflow connections

Environment Variables Required:
- OPENROUTER_API_KEY
- OPENROUTER_SITE_URL (optional, defaults to https://logwhisperer.ai)
- OPENROUTER_APP_NAME (optional, defaults to LogWhispererAI)

Next Steps:
1. Configure environment variables in n8n
2. Import updated workflow to n8n instance
3. Configure PostgreSQL credentials
4. Test with sample log payload

Refs: docs/specs/ai_pipeline.md (section 4.1)
2026-04-02 19:40:42 +02:00
Luca Sacchi Ricciardi
d0f530f757 docs: update AI Pipeline spec to use OpenRouter instead of OpenAI direct
Migrated from OpenAI direct API to OpenRouter for multiple advantages:

Cost Optimization:
- Reduced cost by ~25%: /bin/bash.00015/call (vs /bin/bash.0002/call OpenAI)
- Monthly estimate: ~/bin/bash.15 for 1000 calls (vs /bin/bash.20)

Provider Benefits:
- Access to 300+ AI models (OpenAI, Anthropic, Google, etc.)
- Automatic fallback between providers for 99.9% uptime
- Single API key for all providers
- Unified API interface

Technical Changes:
- Updated endpoint: api.openai.com → openrouter.ai/api/v1
- Model format: gpt-4o-mini → openai/gpt-4o-mini
- Added required headers: HTTP-Referer, X-Title
- Environment variables: OPENAI_API_KEY → OPENROUTER_API_KEY
  + OPENROUTER_SITE_URL (for OpenRouter ranking)
  + OPENROUTER_APP_NAME

Added Sections:
- 3.1 Why OpenRouter? (benefits comparison)
- 3.5 Model Fallback (automatic provider switching)
- Updated all code examples with OpenRouter integration
- Updated test cases (openai_client → openrouter_client)
- Updated cost estimates throughout document

References updated to OpenRouter documentation.

Refs: OpenRouter docs https://openrouter.ai/docs
2026-04-02 19:31:04 +02:00
Luca Sacchi Ricciardi
96ba01b349 docs: add AI Pipeline technical specification
Create comprehensive spec for Sprint 2 Feature 2:

Content:
- System prompt with Metodo Sacchi integration (Safety First, Little Often, Double Check)
- OpenAI GPT-4o-mini configuration (cost: ~/bin/bash.0002/call)
- Complete n8n Code Node JavaScript implementation
- JSON output schema with severity mapping
- Error handling with circuit breaker pattern
- Security guidelines (data sanitization, rate limiting)
- 10 acceptance criteria defined
- 5 test scenarios with expected input/output
- 5 real-world examples (OOM, disk full, connection refused, etc.)
- Implementation checklist for developers

Key Features:
- Safe command generation (destructive commands blacklisted)
- Incremental actions (Little Often principle)
- Confirmation required for uncertain situations (Double Check)
- Fallback when OpenAI unavailable
- Response time < 5s target
- Cost-optimized with GPT-4o-mini

Next: @python-developer implements OpenAI integration in n8n workflow

Refs: workflows/logwhisperer_ingest.json (already created)
2026-04-02 19:15:02 +02:00
Luca Sacchi Ricciardi
3c406ef405 feat: create n8n workflow for secure log ingestion
Implement LogWhisperer_Ingest workflow for Sprint 2 Feature 2:

Workflow Components:
- Webhook trigger: POST /webhook/logwhisperer/ingest
- HMAC-SHA256 validation with timing-safe comparison
- Anti-replay protection (5min timestamp window)
- Data validation: UUID client_id, severity levels, non-empty logs
- PostgreSQL storage with logs table auto-creation
- Conditional routing for critical severity logs

Security Features:
- HMAC signature verification (X-LogWhisperer-Signature header)
- Timestamp validation preventing replay attacks
- Input sanitization before DB insert
- Environment variable LOGWHISPERER_SECRET for shared secret

Documentation:
- workflows/logwhisperer_ingest.json: Export JSON workflow
- workflows/README.md: Installation and usage guide
- workflows/INTEGRATION.md: Bash script integration guide
- workflows/REPORT.md: Implementation report
- workflows/test_workflow.sh: Automated test suite

Metodo Sacchi Applied:
- Safety First: HMAC validation before any processing
- Little Often: Modular nodes, each with single responsibility
- Double Check: Test suite validates all security requirements

Next Steps:
- Configure LOGWHISPERER_SECRET in n8n environment
- Import workflow to n8n instance
- Test end-to-end with secure_logwhisperer.sh
2026-04-02 19:01:40 +02:00
Luca Sacchi Ricciardi
9de40fde2d feat: implement secure bash log ingestion script (Sprint 2)
Implement secure_logwhisperer.sh resolving HIGH severity vulnerabilities:

Security Features:
- Path traversal prevention: validate_log_source() enforces /var/log/ only
- Command injection protection: no eval, array-based commands
- JSON injection fix: jq-based encoding (no manual escaping)
- DLP masking: passwords, emails, API keys, IPs redacted
- HMAC-SHA256 webhook authentication with timestamps
- Atomic file operations preventing race conditions
- HTTPS enforcement for webhook URLs

New Functions:
- validate_log_source(): whitelist /var/log paths, symlink validation
- sanitize_log_line(): DLP + control char removal + truncation
- encode_json_payload(): safe JSON via jq
- generate_hmac_signature(): HMAC-SHA256 for auth
- atomic_write_offset(): tmp+mv atomic writes
- dispatch_webhook_secure(): authenticated HTTPS POST

CLI Commands:
--validate-source, --sanitize-line, --check-deps
--validate-config, --generate-hmac, --atomic-write
--read-offset, --encode-json

Test Results:
- 27/27 security tests passing
- 4/4 integration tests skipped (require webhook)
- All SEC-* requirements met

Documentation:
- Technical spec in docs/specs/bash_ingestion_secure.md
- Test suite in tests/test_secure_logwhisperer.py (31 tests)

Security Audit: Passes all OWASP guidelines
Breaking Changes: Requires jq, openssl dependencies
2026-04-02 18:52:02 +02:00
Luca Sacchi Ricciardi
3a455e48d2 docs: update documentation with MCP configuration and agent catalog
- Add MCP servers documentation (n8n, context7, sequential-thinking)
- Update README.md with complete project structure and requirements.txt
- Transform agents.md into comprehensive agent staff catalog (9 agents)
- Update CHANGELOG.md with [Unreleased] MCP entries
- Fix ingestion_script.md acceptance criteria checkboxes
- Add .opencode/opencode.json to .gitignore for security
- Include new agent configs: n8n_specialist_agent, context_auditor_agent
- Include new skill playbooks: n8n_automation, context7_documentation

Security: API credentials in .opencode/opencode.json are now gitignored
2026-04-02 18:21:21 +02:00
Luca Sacchi Ricciardi
9205c4ef32 docs: update git-history.md with Sprint 1 Project Review
- Add latest commit 88cfe9a to recent commits section

- Update Version 0.1.1 entry with Project Review details

- Update cronologia completa table with new commit

- Update Sprint 1 status to Completed and Approved

- Update statistics: 21 total commits

- Add Project Review reference and Go/No-Go decision
2026-04-02 17:27:47 +02:00
Luca Sacchi Ricciardi
88cfe9af50 docs: update all documentation for Sprint 1 completion
- Update README.md with badges, project status, and improved structure
- Update CHANGELOG.md with Project Review Sprint 1 and version 0.1.1
- Update PRD status to reflect Sprint 1 completion
- Update ingestion script spec status to Completed with review link
- Update Sprint 1 verification report with Project Review reference
- Add comprehensive Sprint 1 Project Review document

Refs: Project Review conducted by agent staff (Product Manager, Tech Lead, Security Auditor)
2026-04-02 17:25:29 +02:00
Luca Sacchi Ricciardi
844294f7b2 docs: update changelog with AGENTS.md documentation entry 2026-04-02 17:04:11 +02:00
Luca Sacchi Ricciardi
b565895df1 docs: update AGENTS.md with complete agent rules and workflow 2026-04-02 16:53:12 +02:00
Luca Sacchi Ricciardi
ffb396a5a5 refactor: reorganize agent configuration structure
- Create individual agent config files in .opencode/agents/
- Add detailed configurations for all 7 agents:
  * tech-lead.md - Architecture validation
  * product-manager.md - Value alignment
  * python-developer.md - TDD Python implementation
  * bash-expert.md - Bash scripting specialist
  * security-auditor.md - Security auditing
  * qa-engineer.md - Testing and coverage
  * documentation-agent.md - Documentation maintenance
- Simplify and optimize docs/1.setup_procedure/agents.md
- Add workflow diagram and structure overview
- Reference detailed configs from main agents.md
2026-04-02 16:48:37 +02:00
Luca Sacchi Ricciardi
8c37e4bc50 docs: add agent staff configuration document
- Define 7 AI agent roles and responsibilities
- Document tools and focus areas for each agent
- Include operational workflow guidelines
- Configure for Spec-Driven and Safety First workflow
2026-04-02 16:40:56 +02:00
Luca Sacchi Ricciardi
a510d5fc68 docs: add git history tracking document
- Create comprehensive git history documentation
- Track all commits with dates, authors, and types
- Include sprint history section
- Add statistics and update instructions
- Maintainable format for future updates
2026-04-02 16:30:44 +02:00
232 changed files with 31261 additions and 115 deletions

41
.env Normal file
View 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
View 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
View File

@@ -20,3 +20,16 @@ htmlcov/
# OS
.DS_Store
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

View 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)

View 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.

View 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

View 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.

View 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)

View 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
```

View 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
```

View 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

View 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

775
.opencode/skills/SKILL.md Normal file
View 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

View 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.

View 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

View 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`

View 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

View 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

File diff suppressed because it is too large Load Diff

View 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.

View 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])
}
```

View 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).

View 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.

View 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)

View 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()
])
```

View 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.

View 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)

View 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.

View 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>
)
}
```

View 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} />
}
```

View 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.

View 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', () => { /* ... */ })
// ...
}
```

View 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.

View File

@@ -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()`.

View 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)

View 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.

View 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)

View 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)
}
```

View 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()
}
})
```

View 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)
}
```

View 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 }
}
```

View 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
```

View 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.

View File

@@ -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

View File

@@ -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.

View File

@@ -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))
```

View File

@@ -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

View File

@@ -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.

View File

@@ -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.

View File

@@ -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>
```

View File

@@ -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).

View File

@@ -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.

View File

@@ -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.

View File

@@ -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
```

View File

@@ -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>
}
```

View File

@@ -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])
```

View File

@@ -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'} />
}
```

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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)
}, [])
}
```

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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>
)
}
```

View File

@@ -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>
}
```

View 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.

View File

@@ -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.

View File

@@ -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.

View 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).

View File

@@ -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()

View 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.

View 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.

File diff suppressed because it is too large Load Diff

View 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.

View 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])
}
```

View 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).

View 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.

View 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)

View 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()
])
```

View 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.

View 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)

View 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.

View 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>
)
}
```

View 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} />
}
```

View 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.

View 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', () => { /* ... */ })
// ...
}
```

View 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.

View File

@@ -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()`.

View 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)

View 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.

View 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)

View 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)
}
```

View 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()
}
})
```

View 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)
}
```

View 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 }
}
```

View 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
```

View 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.

View File

@@ -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

View File

@@ -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.

Some files were not shown because too many files have changed in this diff Show More