Enhance Next.js configuration and dependencies for improved functionality and localization support. Added support for internationalization with next-intl, updated global styles, and integrated new fonts. Removed default home page and updated README with project details and setup instructions.

This commit is contained in:
smhk1376 committed 2026-09-24 14:53:01 +03:30
1 parent 2911dea00b
commit 44f4fa98e2
320 files changed
+31663 -217

No files matched your search

@@ -0,0 +1,28 @@
---
name: design-system-rules
description: >-
Project design-system rules for AUT Open Education: shadcn/ui + Tailwind only.
Use when changing UI, styling, colors, cards, navigation, forms, or loading
states. Read docs/design-system-rules.md and skill shadcn-ui before visual work.
---
# Design System Rules
## Instructions
1. **Before any UI change**, read:
- `docs/design-system-rules.md`
- skill `shadcn-ui` (`.agents/skills/shadcn-ui/SKILL.md`)
- Theme: `src/app/globals.css` (shadcn CSS variables only)
2. Build from `@/components/ui/*` + Tailwind. Add missing pieces with `npx shadcn@latest add`.
3. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `bg-chart-3` — never `ds-*` or `--brand-*`.
4. Extract substantial UI into molecules/organisms; keep pages thin (`.cursor/rules/ui-architecture.mdc`).
5. Material Design skill is methodology only — do not replace AUT colors mapped into shadcn tokens.
6. Complete the checklist in §4 of `docs/design-system-rules.md` before finishing.
## Anti-patterns
- Reviving `.ds-*` utilities or `--brand-*` parallel tokens
- Inventing new hex in components (use theme vars / SVG `var(--accent)`)
- Full section border boxes when `Card` / `Separator` / spacing suffice
- Physical `ml/mr/pl/pr` on RTL without an LTR island
+165
View File
@@ -0,0 +1,165 @@
---
name: material-design
description: >-
Material Design 3 / M3 Expressive principles, color roles, typography scale,
elevation, motion, and anti-patterns. Use when designing or reviewing UI,
building design tokens, choosing component patterns, accessibility defaults,
or when the user mentions Material, M3, design system foundation, or visual consistency.
---
# Material Design
## OVERVIEW
Google's comprehensive open-source design system providing guidelines, components, and tools for building high-quality digital experiences. Launched 2014, evolved to Material 3 (2021), Material 3 Expressive (2025). Unified approach across Android, web, iOS, and Flutter platforms.
**Why this matters**: Accelerates development with pre-built components, ensures accessibility compliance, maintains cross-platform consistency, backed by extensive documentation and community support.
## WHEN TO USE
- Designing Android applications (native design language)
- Creating cross-platform products requiring consistent experience
- Building design systems from established foundation
- Rapid prototyping with pre-built specifications
- Products requiring strong accessibility defaults (WCAG-compliant)
- Teams needing shared designer-developer vocabulary
- Brands wanting modern design without starting from scratch
**Trigger**: Need to ship polished UI quickly or maintain consistency across multiple platforms.
## KEY PRINCIPLES
### 1. Material is the Metaphor
**Concept**: Digital elements behave like physical materials with tactile qualities, depth, and realistic motion.
**Application**:
- Surfaces have elevation (z-axis positioning creating shadows)
- Elements respond to touch with ripple effects
- Transitions maintain spatial relationships
- Depth communicates hierarchy and focus
**Implementation**: Cards at 2dp elevation, FAB at 6dp, navigation drawer at 16dp, modals at 24dp.
### 2. Bold, Graphic, Intentional
**Concept**: Use vibrant colors, prominent typography, and deliberate white space to create clear visual hierarchy.
**Application**:
- Dynamic color system generates cohesive palettes
- Typography scale with consistent hierarchy (Display, Headline, Title, Body, Label)
- Purposeful use of color to guide attention
- Generous spacing for clarity
**Implementation**: Extract brand colors, generate 65 tokens (13 tones × 5 roles), apply type scale.
### 3. Motion Provides Meaning
**Concept**: Animation is not decoration—it guides understanding and maintains context.
**Application**:
- Spring physics for organic, responsive feel (Material 3 Expressive)
- Shared element transitions maintain spatial continuity
- Motion emphasizes hierarchy and relationships
- Respect prefers-reduced-motion for accessibility
**Implementation**: Replace duration-based easing with spring animations, use morphing shapes.
## EXECUTION STEPS
### Phase 1: Establish Foundation
1. **Define color palette** - Use Theme Builder to extract from brand assets
2. **Set up typography scale** - Choose Display/Headline/Title/Body/Label sizes
3. **Configure shape system** - Define corner radius scale (None to Full)
4. **Implement elevation system** - Establish z-axis hierarchy
### Phase 2: Build Component Library
5. **Import Material components** - Use Material UI (React), MDC-Web, or Flutter Material
6. **Customize theme tokens** - Override color, typography, shape as needed
7. **Test accessibility** - Verify contrast ratios, keyboard navigation, screen readers
8. **Create responsive layouts** - Apply 12-column grid with breakpoints (Compact/Medium/Expanded)
### Phase 3: Implement Motion & Refinement
9. **Add spring physics** - Replace linear animations with organic motion
10. **Implement state changes** - Hover, focus, active, disabled states
11. **Test cross-platform** - Verify consistency across web/iOS/Android
12. **Document patterns** - Catalog custom implementations for team reference
## SUCCESS METRICS
- **Development velocity** - 2-3x faster with pre-built components
- **Accessibility compliance** - WCAG AA/AAA pass rate ≥ 95%
- **Cross-platform consistency** - User recognition across platforms ≥ 85%
- **Design-dev handoff time** - 50%+ reduction vs. custom designs
- **User task completion** - Familiar patterns increase success rates
## REAL-WORLD EXAMPLES
### Google Photos
Comprehensive Material 3 implementation demonstrating dynamic color theming that adapts to user wallpaper. Spring animations for photo grid interactions.
### Todoist
Cross-platform task manager using Material Design Web for consistency. Custom color theming while maintaining Material component patterns.
### Cash App
Fintech product using Material elevation and components but customizing colors and shapes for brand differentiation. Passed accessibility audit first attempt.
## ANTI-PATTERNS
**What NOT to do**:
- **Mixing design systems** - Combining Material with HIG or Fluent creates inconsistency
- **Arbitrary elevation** - Random z-axis values break hierarchy
- **Color without testing** - Skipping contrast ratio verification
- **Ignoring breakpoints** - Fixed layouts that break on tablets
- **Custom motion timing** - Replacing Material physics with linear easing
- **Recreating components** - Building from scratch vs. using libraries
- **Overriding accessibility** - Changing touch targets or keyboard navigation
- **Treating as rigid** - Material is flexible; customize thoughtfully
## EDGE CASES
- **Strong brand identity** - Customize color/shape/typography but keep interaction patterns
- **iOS-first products** - Material works on iOS but consider HIG for platform conventions
- **High-security contexts** - Material's bold colors may conflict with conservative aesthetics
- **Low-bandwidth environments** - Material components can be heavy; consider lite versions
- **Highly specialized interfaces** - Complex data tools may need custom components
## INTEGRATION
**Pairs well with**:
- **Design Tokens** - Material 3 built on token architecture
- **Atomic Design** - Component hierarchy methodology
- **Storybook** - Document Material components
- **Figma UI Kits** - Design with official Material templates
- **Accessibility Standards** - WCAG compliance built-in
**Contrasts with**:
- **Human Interface Guidelines** - Apple's iOS/macOS design language
- **Fluent Design** - Microsoft's Windows design system
- **Custom design systems** - Bespoke vs. established framework
## TOOLS & RESOURCES
- **Official site**: m3.material.io (comprehensive documentation)
- **Theme Builder**: Material Theme Builder (Figma plugin)
- **Component libraries**: Material UI (React), MDC-Web, Flutter Material
- **Design kits**: Official Figma/Sketch UI kits
- **Color tool**: Material palette generator
- **Motion guidelines**: Material motion system documentation
## 2025 UPDATE: Material 3 Expressive
Announced at The Android Show (May 2025) for Android 16 and Wear OS 6:
- Spring-based physics replacing duration-based easing
- 35 new morphing shapes with fluid transitions
- Enhanced color expressiveness with more vibrant defaults
- Improved animation smoothness and responsiveness
## FURTHER READING
- **Primary Source**: Material Design 3 documentation (m3.material.io)
- **Implementation**: Material Components libraries for each platform
- **Case Studies**: Google Design Medium publication
- **Related**: *Design Systems* by Alla Kholmatova
- **Advanced**: Building Design Systems (Brad Frost)
## SCORING RATIONALE
**Total: 47/50**
| Criterion | Score | Reasoning |
|-----------|-------|-----------|
| Practitioner | 10/10 | Google ships Material across all products; battle-tested at scale |
| Clarity | 10/10 | Comprehensive docs, code examples, design kits, clear specifications |
| ROI | 10/10 | 2-3x faster development, accessibility built-in, reduces design debt |
| Novelty | 7/10 | Innovative in 2014; now standard but evolving with Expressive |
| Cross-Domain | 10/10 | Works across web, mobile, desktop, wearables, automotive |
**Evidence**: Billions of Android devices, adoption by non-Google products (Todoist, Cash App), open-source community, continuous evolution (Material 3 Expressive 2025).
+33
View File
@@ -0,0 +1,33 @@
---
name: shadcn-ui
description: >-
Use shadcn/ui + Tailwind only for this project's UI. Triggers on UI, styling,
components, cards, forms, navigation, theming, or when the user mentions
shadcn, ui/*, or design tokens. Do not invent parallel ds-* or --brand-* systems.
---
# shadcn/ui for AUT Management Website
## Source of truth
- Docs: https://ui.shadcn.com/docs/installation and https://ui.shadcn.com/docs/installation/next
- Config: `components.json` (style `base-nova`, CSS vars, RTL)
- Styles: `src/app/globals.css` — only Tailwind + `shadcn/tailwind.css` + theme CSS variables
- Primitives: `src/components/ui/*` via `npx shadcn@latest add <name>`
## Rules
1. Build UI from `@/components/ui/*` + Tailwind utilities only.
2. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `border-border`, `bg-card` — never `--brand-*` or `brand-*` classes.
3. Do not create or revive `.ds-*` utilities, SurfaceCard, or DotCta patterns.
4. Prefer `Card`, `Button`, `Separator`, `Sheet`, `NavigationMenu`, `Input`, `Label`, `Tabs`, `Skeleton`, `Badge`.
5. Add missing primitives with the CLI; do not hand-copy stale component APIs.
6. Keep Persian RTL (`dir="rtl"` on layout; `components.json` `"rtl": true`).
7. AUT identity lives only in shadcn theme variables (`--primary`, `--accent`, …).
## Anti-patterns
- Parallel design tokens (`--brand-*`, `ds-card`, `ds-hero`, `ds-cta`)
- Full section boxes with `border border-border` when spacing/`Separator`/`Card` suffice
- Always-on motion (ken-burns, default lift on every card)
---
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,123 @@
# React Best Practices
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
## Structure
- `rules/` - Individual rule files (one per rule)
- `_sections.md` - Section metadata (titles, impacts, descriptions)
- `_template.md` - Template for creating new rules
- `area-description.md` - Individual rule files
- `src/` - Build scripts and utilities
- `metadata.json` - Document metadata (version, organization, abstract)
- __`AGENTS.md`__ - Compiled output (generated)
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
## Getting Started
1. Install dependencies:
```bash
pnpm install
```
2. Build AGENTS.md from rules:
```bash
pnpm build
```
3. Validate rule files:
```bash
pnpm validate
```
4. Extract test cases:
```bash
pnpm extract-tests
```
## Creating a New Rule
1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
- `async-` for Eliminating Waterfalls (Section 1)
- `bundle-` for Bundle Size Optimization (Section 2)
- `server-` for Server-Side Performance (Section 3)
- `client-` for Client-Side Data Fetching (Section 4)
- `rerender-` for Re-render Optimization (Section 5)
- `rendering-` for Rendering Performance (Section 6)
- `js-` for JavaScript Performance (Section 7)
- `advanced-` for Advanced Patterns (Section 8)
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
## Rule File Structure
Each rule file should follow this structure:
```markdown
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description
tags: tag1, tag2, tag3
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example
```
**Correct (description of what's right):**
```typescript
// Good code example
```
Optional explanatory text after examples.
Reference: [Link](https://example.com)
## File Naming Convention
- Files starting with `_` are special (excluded from build)
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
- Section is automatically inferred from filename prefix
- Rules are sorted alphabetically by title within each section
- IDs (e.g., 1.1, 1.2) are auto-generated during build
## Impact Levels
- `CRITICAL` - Highest priority, major performance gains
- `HIGH` - Significant performance improvements
- `MEDIUM-HIGH` - Moderate-high gains
- `MEDIUM` - Moderate performance improvements
- `LOW-MEDIUM` - Low-medium gains
- `LOW` - Incremental improvements
## Scripts
- `pnpm build` - Compile rules into AGENTS.md
- `pnpm validate` - Validate all rule files
- `pnpm extract-tests` - Extract test cases for LLM evaluation
- `pnpm dev` - Build and validate
## Contributing
When adding or modifying rules:
1. Use the correct filename prefix for your section
2. Follow the `_template.md` structure
3. Include clear bad/good examples with explanations
4. Add appropriate tags
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
6. Rules are automatically sorted by title - no need to manage numbers!
## Acknowledgments
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
@@ -0,0 +1,149 @@
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |
## Quick Reference
### 1. Eliminating Waterfalls (CRITICAL)
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### 2. Bundle Size Optimization (CRITICAL)
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### 3. Server-Side Performance (HIGH)
- `server-auth-actions` - Authenticate server actions like API routes
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-dedup-props` - Avoid duplicate serialization in RSC props
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
- `server-after-nonblocking` - Use after() for non-blocking operations
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners
- `client-passive-event-listeners` - Use passive listeners for scroll
- `client-localstorage-schema` - Version and minimize localStorage data
### 5. Re-render Optimization (MEDIUM)
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-memo-with-default-value` - Hoist default non-primitive props
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-derived-state-no-effect` - Derive state during render, not effects
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
- `rerender-transitions` - Use startTransition for non-urgent updates
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
- `rerender-no-inline-components` - Don't define components inside components
### 6. Rendering Performance (MEDIUM)
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals
- `rendering-usetransition-loading` - Prefer useTransition for loading state
- `rendering-resource-hints` - Use React DOM resource hints for preloading
- `rendering-script-defer-async` - Use defer or async on script tags
### 7. JavaScript Performance (LOW-MEDIUM)
- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
- `js-request-idle-callback` - Defer non-critical work to browser idle time
### 8. Advanced Patterns (LOW)
- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-init-once` - Initialize app once per app load
- `advanced-use-latest` - useLatest for stable callback refs
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/async-parallel.md
rules/bundle-barrel-imports.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
@@ -0,0 +1,46 @@
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Eliminating Waterfalls (async)
**Impact:** CRITICAL
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
## 2. Bundle Size Optimization (bundle)
**Impact:** CRITICAL
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
## 3. Server-Side Performance (server)
**Impact:** HIGH
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
## 4. Client-Side Data Fetching (client)
**Impact:** MEDIUM-HIGH
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
## 5. Re-render Optimization (rerender)
**Impact:** MEDIUM
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
## 6. Rendering Performance (rendering)
**Impact:** MEDIUM
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
## 7. JavaScript Performance (js)
**Impact:** LOW-MEDIUM
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
## 8. Advanced Patterns (advanced)
**Impact:** LOW
**Description:** Advanced patterns for specific cases that require careful implementation.
@@ -0,0 +1,28 @@
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description of impact (e.g., "20-50% improvement")
tags: tag1, tag2
---
## Rule Title Here
**Impact: MEDIUM (optional impact description)**
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example here
const bad = example()
```
**Correct (description of what's right):**
```typescript
// Good code example here
const good = example()
```
Reference: [Link to documentation or resource](https://example.com)
@@ -0,0 +1,56 @@
---
title: Do Not Put Effect Events in Dependency Arrays
impact: LOW
impactDescription: avoids unnecessary effect re-runs and lint errors
tags: advanced, hooks, useEffectEvent, dependencies, effects
---
## Do Not Put Effect Events in Dependency Arrays
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
**Incorrect (Effect Event added as a dependency):**
```tsx
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId, handleConnected])
}
```
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
**Correct (depend on reactive values, not the Effect Event):**
```tsx
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId])
}
```
Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
@@ -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: (e) => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
```
**Correct (stable subscription):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
const handlerRef = useRef(handler)
useEffect(() => {
handlerRef.current = handler
}, [handler])
useEffect(() => {
const listener = (e) => handlerRef.current(e)
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: (e) => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
```
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
@@ -0,0 +1,42 @@
---
title: Initialize App Once, Not Per Mount
impact: LOW-MEDIUM
impactDescription: avoids duplicate init in development
tags: initialization, useEffect, app-startup, side-effects
---
## Initialize App Once, Not Per Mount
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
@@ -0,0 +1,39 @@
---
title: useEffectEvent for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useEffectEvent, refs, optimization
---
## useEffectEvent for Stable Callback Refs
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
**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 (using React's useEffectEvent):**
```tsx
import { useEffectEvent } from 'react';
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchEvent = useEffectEvent(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300)
return () => clearTimeout(timeout)
}, [query])
}
```
@@ -0,0 +1,38 @@
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---
## Prevent Waterfall Chains in API Routes
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
**Incorrect (config waits for auth, data waits for both):**
```typescript
export async function GET(request: Request) {
const session = await auth()
const config = await fetchConfig()
const data = await fetchData(session.user.id)
return Response.json({ data, config })
}
```
**Correct (auth and config start immediately):**
```typescript
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id)
])
return Response.json({ data, config })
}
```
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
@@ -0,0 +1,37 @@
---
title: Check Cheap Conditions Before Async Flags
impact: HIGH
impactDescription: avoids unnecessary async work when a synchronous guard already fails
tags: async, await, feature-flags, short-circuit, conditional
---
## Check Cheap Conditions Before Async Flags
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
**Incorrect:**
```typescript
const someFlag = await getFlag()
if (someFlag && someCondition) {
// ...
}
```
**Correct:**
```typescript
if (someCondition) {
const someFlag = await getFlag()
if (someFlag) {
// ...
}
}
```
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
@@ -0,0 +1,82 @@
---
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.
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
@@ -0,0 +1,51 @@
---
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)
}
})
```
**Alternative without extra dependencies:**
We can also create all the promises first, and do `Promise.all()` at the end.
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
@@ -0,0 +1,28 @@
---
title: Promise.all() for Independent Operations
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, promises, waterfalls
---
## Promise.all() for Independent Operations
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
**Incorrect (sequential execution, 3 round trips):**
```typescript
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
```
**Correct (parallel execution, 1 round trip):**
```typescript
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
```
@@ -0,0 +1,99 @@
---
title: Strategic Suspense Boundaries
impact: HIGH
impactDescription: faster initial paint
tags: async, suspense, streaming, layout-shift
---
## Strategic Suspense Boundaries
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
**Incorrect (wrapper blocked by data fetching):**
```tsx
async function Page() {
const data = await fetchData() // Blocks entire page
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
```
The entire layout waits for data even though only the middle section needs it.
**Correct (wrapper shows immediately, data streams in):**
```tsx
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
async function DataDisplay() {
const data = await fetchData() // Only blocks this component
return <div>{data.content}</div>
}
```
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
**Alternative (share promise across components):**
```tsx
function Page() {
// Start fetch immediately, but don't await
const dataPromise = fetchData()
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
)
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Unwraps the promise
return <div>{data.content}</div>
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Reuses the same promise
return <div>{data.summary}</div>
}
```
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
**When NOT to use this pattern:**
- Critical data needed for layout decisions (affects positioning)
- SEO-critical content above the fold
- Small, fast queries where suspense overhead isn't worth it
- When you want to avoid layout shift (loading → content jump)
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
@@ -0,0 +1,63 @@
---
title: Prefer Statically Analyzable Paths
impact: HIGH
impactDescription: avoids accidental broad bundles and file traces
tags: bundle, nextjs, vite, webpack, rollup, esbuild, path
---
## Prefer Statically Analyzable Paths
Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
When analysis becomes too broad, the cost is real:
- Larger server bundles
- Slower builds
- Worse cold starts
- More memory use
### Import Paths
**Incorrect (the bundler cannot tell what may be imported):**
```ts
const PAGE_MODULES = {
home: './pages/home',
settings: './pages/settings',
} as const
const Page = await import(PAGE_MODULES[pageName])
```
**Correct (use an explicit map of allowed modules):**
```ts
const PAGE_MODULES = {
home: () => import('./pages/home'),
settings: () => import('./pages/settings'),
} as const
const Page = await PAGE_MODULES[pageName]()
```
### File-System Paths
**Incorrect (a 2-value enum still hides the final path from static analysis):**
```ts
const baseDir = path.join(process.cwd(), 'content/' + contentKind)
```
**Correct (make each final path literal at the callsite):**
```ts
const baseDir =
kind === ContentKind.Blog
? path.join(process.cwd(), 'content/blog')
: path.join(process.cwd(), 'content/docs')
```
In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
@@ -0,0 +1,60 @@
---
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 - Next.js 13.5+ (recommended):**
```js
// next.config.js - automatically optimizes barrel imports at build time
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
```
```tsx
// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from 'lucide-react'
// Full TypeScript support, no manual path wrangling
```
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
**Correct - Direct imports (non-Next.js projects):**
```tsx
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
```
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
@@ -0,0 +1,31 @@
---
title: Conditional Module Loading
impact: HIGH
impactDescription: loads large data only when needed
tags: bundle, conditional-loading, lazy-loading
---
## Conditional Module Loading
Load large data or modules only when a feature is activated.
**Example (lazy-load animation frames):**
```tsx
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
const [frames, setFrames] = useState<Frame[] | null>(null)
useEffect(() => {
if (enabled && !frames && typeof window !== 'undefined') {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames, setEnabled])
if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}
```
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
@@ -0,0 +1,49 @@
---
title: Defer Non-Critical Third-Party Libraries
impact: MEDIUM
impactDescription: loads after hydration
tags: bundle, third-party, analytics, defer
---
## Defer Non-Critical Third-Party Libraries
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
**Incorrect (blocks initial bundle):**
```tsx
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
**Correct (loads after hydration):**
```tsx
import dynamic from 'next/dynamic'
const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
@@ -0,0 +1,35 @@
---
title: Dynamic Imports for Heavy Components
impact: CRITICAL
impactDescription: directly affects TTI and LCP
tags: bundle, dynamic-import, code-splitting, next-dynamic
---
## Dynamic Imports for Heavy Components
Use `next/dynamic` to lazy-load large components not needed on initial render.
**Incorrect (Monaco bundles with main chunk ~300KB):**
```tsx
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
**Correct (Monaco loads on demand):**
```tsx
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
() => import('./monaco-editor').then(m => m.MonacoEditor),
{ ssr: false }
)
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
@@ -0,0 +1,50 @@
---
title: Preload Based on User Intent
impact: MEDIUM
impactDescription: reduces perceived latency
tags: bundle, preload, user-intent, hover
---
## Preload Based on User Intent
Preload heavy bundles before they're needed to reduce perceived latency.
**Example (preload on hover/focus):**
```tsx
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== 'undefined') {
void import('./monaco-editor')
}
}
return (
<button
onMouseEnter={preload}
onFocus={preload}
onClick={onClick}
>
Open Editor
</button>
)
}
```
**Example (preload when feature flag is enabled):**
```tsx
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled && typeof window !== 'undefined') {
void import('./monaco-editor').then(mod => mod.init())
}
}, [flags.editorEnabled])
return <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
@@ -0,0 +1,74 @@
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---
## Deduplicate Global Event Listeners
Use `useSWRSubscription()` to share global event listeners across component instances.
**Incorrect (N instances = N listeners):**
```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [key, callback])
}
```
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
**Correct (N instances = 1 listener):**
```tsx
import useSWRSubscription from 'swr/subscription'
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set())
}
keyCallbacks.get(key)!.add(callback)
return () => {
const set = keyCallbacks.get(key)
if (set) {
set.delete(callback)
if (set.size === 0) {
keyCallbacks.delete(key)
}
}
}
}, [key, callback])
useSWRSubscription('global-keydown', () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach(cb => cb())
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
})
}
function Profile() {
// Multiple shortcuts will share the same listener
useKeyboardShortcut('p', () => { /* ... */ })
useKeyboardShortcut('k', () => { /* ... */ })
// ...
}
```
@@ -0,0 +1,71 @@
---
title: Version and Minimize localStorage Data
impact: MEDIUM
impactDescription: prevents schema conflicts, reduces storage size
tags: client, localStorage, storage, versioning, data-minimization
---
## Version and Minimize localStorage Data
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
**Incorrect:**
```typescript
// No version, stores everything, no error handling
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
const data = localStorage.getItem('userConfig')
```
**Correct:**
```typescript
const VERSION = 'v2'
function saveConfig(config: { theme: string; language: string }) {
try {
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
} catch {
// Throws in incognito/private browsing, quota exceeded, or disabled
}
}
function loadConfig() {
try {
const data = localStorage.getItem(`userConfig:${VERSION}`)
return data ? JSON.parse(data) : null
} catch {
return null
}
}
// Migration from v1 to v2
function migrate() {
try {
const v1 = localStorage.getItem('userConfig:v1')
if (v1) {
const old = JSON.parse(v1)
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
localStorage.removeItem('userConfig:v1')
}
} catch {}
}
```
**Store minimal fields from server responses:**
```typescript
// User object has 20+ fields, only store what UI needs
function cachePrefs(user: FullUser) {
try {
localStorage.setItem('prefs:v1', JSON.stringify({
theme: user.preferences.theme,
notifications: user.preferences.notifications
}))
} catch {}
}
```
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
@@ -0,0 +1,48 @@
---
title: Use Passive Event Listeners for Scrolling Performance
impact: MEDIUM
impactDescription: eliminates scroll delay caused by event listeners
tags: client, event-listeners, scrolling, performance, touch, wheel
---
## Use Passive Event Listeners for Scrolling Performance
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
**Incorrect:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch)
document.addEventListener('wheel', handleWheel)
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Correct:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch, { passive: true })
document.addEventListener('wheel', handleWheel, { passive: true })
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
@@ -0,0 +1,56 @@
---
title: Use SWR for Automatic Deduplication
impact: MEDIUM-HIGH
impactDescription: automatic deduplication
tags: client, swr, deduplication, data-fetching
---
## Use SWR for Automatic Deduplication
SWR enables request deduplication, caching, and revalidation across component instances.
**Incorrect (no deduplication, each instance fetches):**
```tsx
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
```
**Correct (multiple instances share one request):**
```tsx
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
```
**For immutable data:**
```tsx
import { useImmutableSWR } from '@/lib/swr'
function StaticContent() {
const { data } = useImmutableSWR('/api/config', fetcher)
}
```
**For mutations:**
```tsx
import { useSWRMutation } from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
@@ -0,0 +1,107 @@
---
title: Avoid Layout Thrashing
impact: MEDIUM
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
tags: javascript, dom, css, performance, reflow, layout-thrashing
---
## Avoid Layout Thrashing
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
```
**Incorrect (interleaved reads and writes force reflows):**
```typescript
function layoutThrashing(element: HTMLElement) {
element.style.width = '100px'
const width = element.offsetWidth // Forces reflow
element.style.height = '200px'
const height = element.offsetHeight // Forces another reflow
}
```
**Correct (batch writes, then read once):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect()
}
```
**Correct (batch reads, then writes):**
```typescript
function avoidThrashing(element: HTMLElement) {
// Read phase - all layout queries first
const rect1 = element.getBoundingClientRect()
const offsetWidth = element.offsetWidth
const offsetHeight = element.offsetHeight
// Write phase - all style changes after
element.style.width = '100px'
element.style.height = '200px'
}
```
**Better: use CSS classes**
```css
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
```
```typescript
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
const { width, height } = element.getBoundingClientRect()
}
```
**React example:**
```tsx
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
const width = ref.current.offsetWidth // Forces layout
ref.current.style.height = '200px'
}
}, [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. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
@@ -0,0 +1,80 @@
---
title: Cache Repeated Function Calls
impact: MEDIUM
impactDescription: avoid redundant computation
tags: javascript, cache, memoization, performance
---
## Cache Repeated Function Calls
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
**Incorrect (redundant computation):**
```typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Correct (cached results):**
```typescript
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Simpler pattern for single-value functions:**
```typescript
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
@@ -0,0 +1,28 @@
---
title: Cache Property Access in Loops
impact: LOW-MEDIUM
impactDescription: reduces lookups
tags: javascript, loops, optimization, caching
---
## Cache Property Access in Loops
Cache object property lookups in hot paths.
**Incorrect (3 lookups × N iterations):**
```typescript
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value)
}
```
**Correct (1 lookup total):**
```typescript
const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
process(value)
}
```
@@ -0,0 +1,70 @@
---
title: Cache Storage API Calls
impact: LOW-MEDIUM
impactDescription: reduces expensive I/O
tags: javascript, localStorage, storage, caching, performance
---
## Cache Storage API Calls
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
**Incorrect (reads storage on every call):**
```typescript
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads
```
**Correct (Map cache):**
```typescript
const storageCache = new Map<string, string | null>()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
**Cookie caching:**
```typescript
let cookieCache: Record<string, string> | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
```
**Important (invalidate on external changes):**
If storage can change externally (another tab, server-set cookies), invalidate cache:
```typescript
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})
```
@@ -0,0 +1,32 @@
---
title: Combine Multiple Array Iterations
impact: LOW-MEDIUM
impactDescription: reduces iterations
tags: javascript, arrays, loops, performance
---
## Combine Multiple Array Iterations
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
**Incorrect (3 iterations):**
```typescript
const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)
```
**Correct (1 iteration):**
```typescript
const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []
for (const user of users) {
if (user.isAdmin) admins.push(user)
if (user.isTester) testers.push(user)
if (!user.isActive) inactive.push(user)
}
```
@@ -0,0 +1,50 @@
---
title: Early Return from Functions
impact: LOW-MEDIUM
impactDescription: avoids unnecessary computation
tags: javascript, functions, optimization, early-return
---
## Early Return from Functions
Return early when result is determined to skip unnecessary processing.
**Incorrect (processes all items even after finding answer):**
```typescript
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError = true
errorMessage = 'Name required'
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
```
**Correct (returns immediately on first error):**
```typescript
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
```
@@ -0,0 +1,60 @@
---
title: Use flatMap to Map and Filter in One Pass
impact: LOW-MEDIUM
impactDescription: eliminates intermediate array
tags: javascript, arrays, flatMap, filter, performance
---
## Use flatMap to Map and Filter in One Pass
**Impact: LOW-MEDIUM (eliminates intermediate array)**
Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
**Incorrect (2 iterations, intermediate array):**
```typescript
const userNames = users
.map(user => user.isActive ? user.name : null)
.filter(Boolean)
```
**Correct (1 iteration, no intermediate array):**
```typescript
const userNames = users.flatMap(user =>
user.isActive ? [user.name] : []
)
```
**More examples:**
```typescript
// Extract valid emails from responses
// Before
const emails = responses
.map(r => r.success ? r.data.email : null)
.filter(Boolean)
// After
const emails = responses.flatMap(r =>
r.success ? [r.data.email] : []
)
// Parse and filter valid numbers
// Before
const numbers = strings
.map(s => parseInt(s, 10))
.filter(n => !isNaN(n))
// After
const numbers = strings.flatMap(s => {
const n = parseInt(s, 10)
return isNaN(n) ? [] : [n]
})
```
**When to use:**
- Transforming items while filtering some out
- Conditional mapping where some inputs produce no output
- Parsing/validating where invalid inputs should be skipped
@@ -0,0 +1,45 @@
---
title: Hoist RegExp Creation
impact: LOW-MEDIUM
impactDescription: avoids recreation
tags: javascript, regexp, optimization, memoization
---
## Hoist RegExp Creation
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
**Incorrect (new RegExp every render):**
```tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Correct (memoize or hoist):**
```tsx
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Warning (global regex has mutable state):**
Global regex (`/g`) has mutable `lastIndex` state:
```typescript
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0
```
@@ -0,0 +1,37 @@
---
title: Build Index Maps for Repeated Lookups
impact: LOW-MEDIUM
impactDescription: 1M ops to 2K ops
tags: javascript, map, indexing, optimization, performance
---
## Build Index Maps for Repeated Lookups
Multiple `.find()` calls by the same key should use a Map.
**Incorrect (O(n) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
return orders.map(order => ({
...order,
user: users.find(u => u.id === order.userId)
}))
}
```
**Correct (O(1) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map(u => [u.id, u]))
return orders.map(order => ({
...order,
user: userById.get(order.userId)
}))
}
```
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
@@ -0,0 +1,49 @@
---
title: Early Length Check for Array Comparisons
impact: MEDIUM-HIGH
impactDescription: avoids expensive operations when lengths differ
tags: javascript, arrays, performance, optimization, comparison
---
## Early Length Check for Array Comparisons
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join()
}
```
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
@@ -0,0 +1,82 @@
---
title: Use Loop for Min/Max Instead of Sort
impact: LOW
impactDescription: O(n) instead of O(n log n)
tags: javascript, arrays, performance, sorting, algorithms
---
## Use Loop for Min/Max Instead of Sort
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
```typescript
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}
```
Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
```typescript
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}
```
Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
```typescript
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
@@ -0,0 +1,105 @@
---
title: Defer Non-Critical Work with requestIdleCallback
impact: MEDIUM
impactDescription: keeps UI responsive during background tasks
tags: javascript, performance, idle, scheduling, analytics
---
## Defer Non-Critical Work with requestIdleCallback
**Impact: MEDIUM (keeps UI responsive during background tasks)**
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
**Incorrect (blocks main thread during user interaction):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// These block the main thread immediately
analytics.track('search', { query })
saveToRecentSearches(query)
prefetchTopResults(results.slice(0, 3))
}
```
**Correct (defers non-critical work to idle time):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track('search', { query })
})
requestIdleCallback(() => {
saveToRecentSearches(query)
})
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3))
})
}
```
**With timeout for required work:**
```typescript
// Ensure analytics fires within 2 seconds even if browser stays busy
requestIdleCallback(
() => analytics.track('page_view', { path: location.pathname }),
{ timeout: 2000 }
)
```
**Chunking large tasks:**
```typescript
function processLargeDataset(items: Item[]) {
let index = 0
function processChunk(deadline: IdleDeadline) {
// Process items while we have idle time (aim for <50ms chunks)
while (index < items.length && deadline.timeRemaining() > 0) {
processItem(items[index])
index++
}
// Schedule next chunk if more items remain
if (index < items.length) {
requestIdleCallback(processChunk)
}
}
requestIdleCallback(processChunk)
}
```
**With fallback for unsupported browsers:**
```typescript
const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
scheduleIdleWork(() => {
// Non-critical work
})
```
**When to use:**
- Analytics and telemetry
- Saving state to localStorage/IndexedDB
- Prefetching resources for likely next actions
- Processing non-urgent data transformations
- Lazy initialization of non-critical features
**When NOT to use:**
- User-initiated actions that need immediate feedback
- Rendering updates the user is waiting for
- Time-sensitive operations
@@ -0,0 +1,24 @@
---
title: Use Set/Map for O(1) Lookups
impact: LOW-MEDIUM
impactDescription: O(n) to O(1)
tags: javascript, set, map, data-structures, performance
---
## Use Set/Map for O(1) Lookups
Convert arrays to Set/Map for repeated membership checks.
**Incorrect (O(n) per check):**
```typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
```
**Correct (O(1) per check):**
```typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
```
@@ -0,0 +1,57 @@
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
```
**Other immutable array methods:**
- `.toSorted()` - immutable sort
- `.toReversed()` - immutable reverse
- `.toSpliced()` - immutable splice
- `.with()` - immutable element replacement
@@ -0,0 +1,26 @@
---
title: Use Activity Component for Show/Hide
impact: MEDIUM
impactDescription: preserves state/DOM
tags: rendering, activity, visibility, state-preservation
---
## Use Activity Component for Show/Hide
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
**Usage:**
```tsx
import { Activity } from 'react'
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? 'visible' : 'hidden'}>
<ExpensiveMenu />
</Activity>
)
}
```
Avoids expensive re-renders and state loss.
@@ -0,0 +1,47 @@
---
title: Animate SVG Wrapper Instead of SVG Element
impact: LOW
impactDescription: enables hardware acceleration
tags: rendering, svg, css, animation, performance
---
## Animate SVG Wrapper Instead of SVG Element
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
**Incorrect (animating SVG directly - no hardware acceleration):**
```tsx
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
```
**Correct (animating wrapper div - hardware accelerated):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
```
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
@@ -0,0 +1,40 @@
---
title: Use Explicit Conditional Rendering
impact: LOW
impactDescription: prevents rendering 0 or NaN
tags: rendering, conditional, jsx, falsy-values
---
## Use Explicit Conditional Rendering
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
**Incorrect (renders "0" when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count && <span className="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
**Correct (renders nothing when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
@@ -0,0 +1,38 @@
---
title: CSS content-visibility for Long Lists
impact: HIGH
impactDescription: faster initial render
tags: rendering, css, content-visibility, long-lists
---
## CSS content-visibility for Long Lists
Apply `content-visibility: auto` to defer off-screen rendering.
**CSS:**
```css
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
```
**Example:**
```tsx
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map(msg => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
)
}
```
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
@@ -0,0 +1,46 @@
---
title: Hoist Static JSX Elements
impact: LOW
impactDescription: avoids re-creation
tags: rendering, jsx, static, optimization
---
## Hoist Static JSX Elements
Extract static JSX outside components to avoid re-creation.
**Incorrect (recreates element every render):**
```tsx
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />
}
function Container() {
return (
<div>
{loading && <LoadingSkeleton />}
</div>
)
}
```
**Correct (reuses same element):**
```tsx
const loadingSkeleton = (
<div className="animate-pulse h-20 bg-gray-200" />
)
function Container() {
return (
<div>
{loading && loadingSkeleton}
</div>
)
}
```
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
@@ -0,0 +1,82 @@
---
title: Prevent Hydration Mismatch Without Flickering
impact: MEDIUM
impactDescription: avoids visual flicker and hydration errors
tags: rendering, ssr, hydration, localStorage, flicker
---
## Prevent Hydration Mismatch Without Flickering
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
**Incorrect (breaks SSR):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem('theme') || 'light'
return (
<div className={theme}>
{children}
</div>
)
}
```
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<div className={theme}>
{children}
</div>
)
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
```
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
@@ -0,0 +1,30 @@
---
title: Suppress Expected Hydration Mismatches
impact: LOW-MEDIUM
impactDescription: avoids noisy hydration warnings for known differences
tags: rendering, hydration, ssr, nextjs
---
## Suppress Expected Hydration Mismatches
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
**Incorrect (known mismatch warnings):**
```tsx
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>
}
```
**Correct (suppress expected mismatch only):**
```tsx
function Timestamp() {
return (
<span suppressHydrationWarning>
{new Date().toLocaleString()}
</span>
)
}
```
@@ -0,0 +1,85 @@
---
title: Use React DOM Resource Hints
impact: HIGH
impactDescription: reduces load time for critical resources
tags: rendering, preload, preconnect, prefetch, resource-hints
---
## Use React DOM Resource Hints
**Impact: HIGH (reduces load time for critical resources)**
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
- **`preinitModule(href)`**: Fetch and evaluate an ES module
**Example (preconnect to third-party APIs):**
```tsx
import { preconnect, prefetchDNS } from 'react-dom'
export default function App() {
prefetchDNS('https://analytics.example.com')
preconnect('https://api.example.com')
return <main>{/* content */}</main>
}
```
**Example (preload critical fonts and styles):**
```tsx
import { preload, preinit } from 'react-dom'
export default function RootLayout({ children }) {
// Preload font file
preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
// Fetch and apply critical stylesheet immediately
preinit('/styles/critical.css', { as: 'style' })
return (
<html>
<body>{children}</body>
</html>
)
}
```
**Example (preload modules for code-split routes):**
```tsx
import { preloadModule, preinitModule } from 'react-dom'
function Navigation() {
const preloadDashboard = () => {
preloadModule('/dashboard.js', { as: 'script' })
}
return (
<nav>
<a href="/dashboard" onMouseEnter={preloadDashboard}>
Dashboard
</a>
</nav>
)
}
```
**When to use each:**
| API | Use case |
|-----|----------|
| `prefetchDNS` | Third-party domains you'll connect to later |
| `preconnect` | APIs or CDNs you'll fetch from immediately |
| `preload` | Critical resources needed for current page |
| `preloadModule` | JS modules for likely next navigation |
| `preinit` | Stylesheets/scripts that must execute early |
| `preinitModule` | ES modules that must execute early |
Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
@@ -0,0 +1,68 @@
---
title: Use defer or async on Script Tags
impact: HIGH
impactDescription: eliminates render-blocking
tags: rendering, script, defer, async, performance
---
## Use defer or async on Script Tags
**Impact: HIGH (eliminates render-blocking)**
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
**Incorrect (blocks rendering):**
```tsx
export default function Document() {
return (
<html>
<head>
<script src="https://example.com/analytics.js" />
<script src="/scripts/utils.js" />
</head>
<body>{/* content */}</body>
</html>
)
}
```
**Correct (non-blocking):**
```tsx
export default function Document() {
return (
<html>
<head>
{/* Independent script - use async */}
<script src="https://example.com/analytics.js" async />
{/* DOM-dependent script - use defer */}
<script src="/scripts/utils.js" defer />
</head>
<body>{/* content */}</body>
</html>
)
}
```
**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
```tsx
import Script from 'next/script'
export default function Page() {
return (
<>
<Script src="https://example.com/analytics.js" strategy="afterInteractive" />
<Script src="/scripts/utils.js" strategy="beforeInteractive" />
</>
)
}
```
Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
@@ -0,0 +1,28 @@
---
title: Optimize SVG Precision
impact: LOW
impactDescription: reduces file size
tags: rendering, svg, optimization, svgo
---
## Optimize SVG Precision
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
**Incorrect (excessive precision):**
```svg
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
```
**Correct (1 decimal place):**
```svg
<path d="M 10.3 20.8 L 30.9 40.2" />
```
**Automate with SVGO:**
```bash
npx svgo --precision=1 --multipass icon.svg
```
@@ -0,0 +1,75 @@
---
title: Use useTransition Over Manual Loading States
impact: LOW
impactDescription: reduces re-renders and improves code clarity
tags: rendering, transitions, useTransition, loading, state
---
## Use useTransition Over Manual Loading States
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
**Incorrect (manual loading state):**
```tsx
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const handleSearch = async (value: string) => {
setIsLoading(true)
setQuery(value)
const data = await fetchResults(value)
setResults(data)
setIsLoading(false)
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isLoading && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Correct (useTransition with built-in pending state):**
```tsx
import { useTransition, useState } from 'react'
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
const handleSearch = (value: string) => {
setQuery(value) // Update input immediately
startTransition(async () => {
// Fetch and update results
const data = await fetchResults(value)
setResults(data)
})
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Benefits:**
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
- **Error resilience**: Pending state correctly resets even if the transition throws
- **Better responsiveness**: Keeps the UI responsive during updates
- **Interrupt handling**: New transitions automatically cancel pending ones
Reference: [useTransition](https://react.dev/reference/react/useTransition)
@@ -0,0 +1,39 @@
---
title: Defer State Reads to Usage Point
impact: MEDIUM
impactDescription: avoids unnecessary subscriptions
tags: rerender, searchParams, localStorage, optimization
---
## Defer State Reads to Usage Point
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
**Incorrect (subscribes to all searchParams changes):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const searchParams = useSearchParams()
const handleShare = () => {
const ref = searchParams.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
**Correct (reads on demand, no subscription):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search)
const ref = params.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
@@ -0,0 +1,45 @@
---
title: Narrow Effect Dependencies
impact: LOW
impactDescription: minimizes effect re-runs
tags: rerender, useEffect, dependencies, optimization
---
## Narrow Effect Dependencies
Specify primitive dependencies instead of objects to minimize effect re-runs.
**Incorrect (re-runs on any user field change):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user])
```
**Correct (re-runs only when id changes):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user.id])
```
**For derived state, compute outside effect:**
```tsx
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode()
}
}, [width])
// Correct: runs only on boolean transition
const isMobile = width < 768
useEffect(() => {
if (isMobile) {
enableMobileMode()
}
}, [isMobile])
```
@@ -0,0 +1,40 @@
---
title: Calculate Derived State During Rendering
impact: MEDIUM
impactDescription: avoids redundant renders and state drift
tags: rerender, derived-state, useEffect, state
---
## Calculate Derived State During Rendering
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
**Incorrect (redundant state and effect):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const [fullName, setFullName] = useState('')
useEffect(() => {
setFullName(firstName + ' ' + lastName)
}, [firstName, lastName])
return <p>{fullName}</p>
}
```
**Correct (derive during render):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const fullName = firstName + ' ' + lastName
return <p>{fullName}</p>
}
```
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
@@ -0,0 +1,29 @@
---
title: Subscribe to Derived State
impact: MEDIUM
impactDescription: reduces re-render frequency
tags: rerender, derived-state, media-query, optimization
---
## Subscribe to Derived State
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
**Incorrect (re-renders on every pixel change):**
```tsx
function Sidebar() {
const width = useWindowWidth() // updates continuously
const isMobile = width < 768
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
**Correct (re-renders only when boolean changes):**
```tsx
function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
@@ -0,0 +1,74 @@
---
title: Use Functional setState Updates
impact: MEDIUM
impactDescription: prevents stale closures and unnecessary callback recreations
tags: react, hooks, useState, useCallback, callbacks, closures
---
## Use Functional setState Updates
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
**Incorrect (requires state as dependency):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items]) // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter(item => item.id !== id))
}, []) // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
**Correct (stable callbacks, no stale closures):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, []) // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems(curr => curr.filter(item => item.id !== id))
}, []) // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
**Benefits:**
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
**When to use functional updates:**
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
**When direct updates are fine:**
- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
@@ -0,0 +1,58 @@
---
title: Use Lazy State Initialization
impact: MEDIUM
impactDescription: wasted computation on every render
tags: react, hooks, useState, performance, initialization
---
## Use Lazy State Initialization
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
**Incorrect (runs on every render):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
const [query, setQuery] = useState('')
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs on every render
const [settings, setSettings] = useState(
JSON.parse(localStorage.getItem('settings') || '{}')
)
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
**Correct (runs only once):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
const [query, setQuery] = useState('')
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs only on initial render
const [settings, setSettings] = useState(() => {
const stored = localStorage.getItem('settings')
return stored ? JSON.parse(stored) : {}
})
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
@@ -0,0 +1,38 @@
---
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
impact: MEDIUM
impactDescription: restores memoization by using a constant for default value
tags: rerender, memo, optimization
---
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
To address this issue, extract the default value into a constant.
**Incorrect (`onClick` has different values on every rerender):**
```tsx
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
**Correct (stable default value):**
```tsx
const NOOP = () => {};
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
@@ -0,0 +1,44 @@
---
title: Extract to Memoized Components
impact: MEDIUM
impactDescription: enables early returns
tags: rerender, memo, useMemo, optimization
---
## Extract to Memoized Components
Extract expensive work into memoized components to enable early returns before computation.
**Incorrect (computes avatar even when loading):**
```tsx
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user)
return <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
@@ -0,0 +1,45 @@
---
title: Put Interaction Logic in Event Handlers
impact: MEDIUM
impactDescription: avoids effect re-runs and duplicate side effects
tags: rerender, useEffect, events, side-effects, dependencies
---
## Put Interaction Logic in Event Handlers
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
**Incorrect (event modeled as state + effect):**
```tsx
function Form() {
const [submitted, setSubmitted] = useState(false)
const theme = useContext(ThemeContext)
useEffect(() => {
if (submitted) {
post('/api/register')
showToast('Registered', theme)
}
}, [submitted, theme])
return <button onClick={() => setSubmitted(true)}>Submit</button>
}
```
**Correct (do it in the handler):**
```tsx
function Form() {
const theme = useContext(ThemeContext)
function handleSubmit() {
post('/api/register')
showToast('Registered', theme)
}
return <button onClick={handleSubmit}>Submit</button>
}
```
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
@@ -0,0 +1,82 @@
---
title: Don't Define Components Inside Components
impact: HIGH
impactDescription: prevents remount on every render
tags: rerender, components, remount, performance
---
## Don't Define Components Inside Components
**Impact: HIGH (prevents remount on every render)**
Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
A common reason developers do this is to access parent variables without passing props. Always pass props instead.
**Incorrect (remounts on every render):**
```tsx
function UserProfile({ user, theme }) {
// Defined inside to access `theme` - BAD
const Avatar = () => (
<img
src={user.avatarUrl}
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
/>
)
// Defined inside to access `user` - BAD
const Stats = () => (
<div>
<span>{user.followers} followers</span>
<span>{user.posts} posts</span>
</div>
)
return (
<div>
<Avatar />
<Stats />
</div>
)
}
```
Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
**Correct (pass props instead):**
```tsx
function Avatar({ src, theme }: { src: string; theme: string }) {
return (
<img
src={src}
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
/>
)
}
function Stats({ followers, posts }: { followers: number; posts: number }) {
return (
<div>
<span>{followers} followers</span>
<span>{posts} posts</span>
</div>
)
}
function UserProfile({ user, theme }) {
return (
<div>
<Avatar src={user.avatarUrl} theme={theme} />
<Stats followers={user.followers} posts={user.posts} />
</div>
)
}
```
**Symptoms of this bug:**
- Input fields lose focus on every keystroke
- Animations restart unexpectedly
- `useEffect` cleanup/setup runs on every parent render
- Scroll position resets inside the component
@@ -0,0 +1,35 @@
---
title: Do not wrap a simple expression with a primitive result type in useMemo
impact: LOW-MEDIUM
impactDescription: wasted computation on every render
tags: rerender, useMemo, optimization
---
## Do not wrap a simple expression with a primitive result type in useMemo
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
**Incorrect:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = useMemo(() => {
return user.isLoading || notifications.isLoading
}, [user.isLoading, notifications.isLoading])
if (isLoading) return <Skeleton />
// return some markup
}
```
**Correct:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = user.isLoading || notifications.isLoading
if (isLoading) return <Skeleton />
// return some markup
}
```
@@ -0,0 +1,64 @@
---
title: Split Combined Hook Computations
impact: MEDIUM
impactDescription: avoids recomputing independent steps
tags: rerender, useMemo, useEffect, dependencies, optimization
---
## Split Combined Hook Computations
When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
**Incorrect (changing `sortOrder` recomputes filtering):**
```tsx
const sortedProducts = useMemo(() => {
const filtered = products.filter((p) => p.category === category)
const sorted = filtered.toSorted((a, b) =>
sortOrder === "asc" ? a.price - b.price : b.price - a.price
)
return sorted
}, [products, category, sortOrder])
```
**Correct (filtering only recomputes when products or category change):**
```tsx
const filteredProducts = useMemo(
() => products.filter((p) => p.category === category),
[products, category]
)
const sortedProducts = useMemo(
() =>
filteredProducts.toSorted((a, b) =>
sortOrder === "asc" ? a.price - b.price : b.price - a.price
),
[filteredProducts, sortOrder]
)
```
This pattern also applies to `useEffect` when combining unrelated side effects:
**Incorrect (both effects run when either dependency changes):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
document.title = `${pageTitle} | My App`
}, [pathname, pageTitle])
```
**Correct (effects run independently):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
}, [pathname])
useEffect(() => {
document.title = `${pageTitle} | My App`
}, [pageTitle])
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
@@ -0,0 +1,40 @@
---
title: Use Transitions for Non-Urgent Updates
impact: MEDIUM
impactDescription: maintains UI responsiveness
tags: rerender, transitions, startTransition, performance
---
## Use Transitions for Non-Urgent Updates
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
**Incorrect (blocks UI on every scroll):**
```tsx
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => setScrollY(window.scrollY)
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
**Correct (non-blocking updates):**
```tsx
import { startTransition } from 'react'
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY))
}
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
@@ -0,0 +1,59 @@
---
title: Use useDeferredValue for Expensive Derived Renders
impact: MEDIUM
impactDescription: keeps input responsive during heavy computation
tags: rerender, useDeferredValue, optimization, concurrent
---
## Use useDeferredValue for Expensive Derived Renders
When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
**Incorrect (input feels laggy while filtering):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState('')
const filtered = items.filter(item => fuzzyMatch(item, query))
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ResultsList results={filtered} />
</>
)
}
```
**Correct (input stays snappy, results render when ready):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState('')
const deferredQuery = useDeferredValue(query)
const filtered = useMemo(
() => items.filter(item => fuzzyMatch(item, deferredQuery)),
[items, deferredQuery]
)
const isStale = query !== deferredQuery
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.7 : 1 }}>
<ResultsList results={filtered} />
</div>
</>
)
}
```
**When to use:**
- Filtering/searching large lists
- Expensive visualizations (charts, graphs) reacting to input
- Any derived state that causes noticeable render delays
**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
@@ -0,0 +1,73 @@
---
title: Use useRef for Transient Values
impact: MEDIUM
impactDescription: avoids unnecessary re-renders on frequent updates
tags: rerender, useref, state, performance
---
## Use useRef for Transient Values
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
**Incorrect (renders every update):**
```tsx
function Tracker() {
const [lastX, setLastX] = useState(0)
useEffect(() => {
const onMove = (e: MouseEvent) => setLastX(e.clientX)
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
style={{
position: 'fixed',
top: 0,
left: lastX,
width: 8,
height: 8,
background: 'black',
}}
/>
)
}
```
**Correct (no re-render for tracking):**
```tsx
function Tracker() {
const lastXRef = useRef(0)
const dotRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const onMove = (e: MouseEvent) => {
lastXRef.current = e.clientX
const node = dotRef.current
if (node) {
node.style.transform = `translateX(${e.clientX}px)`
}
}
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
ref={dotRef}
style={{
position: 'fixed',
top: 0,
left: 0,
width: 8,
height: 8,
background: 'black',
transform: 'translateX(0px)',
}}
/>
)
}
```
@@ -0,0 +1,73 @@
---
title: Use after() for Non-Blocking Operations
impact: MEDIUM
impactDescription: faster response times
tags: server, async, logging, analytics, side-effects
---
## Use after() for Non-Blocking Operations
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
**Incorrect (blocks response):**
```tsx
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Logging blocks the response
const userAgent = request.headers.get('user-agent') || 'unknown'
await logUserAction({ userAgent })
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
**Correct (non-blocking):**
```tsx
import { after } from 'next/server'
import { headers, cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Log after response is sent
after(async () => {
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
logUserAction({ sessionCookie, userAgent })
})
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
The response is sent immediately while logging happens in the background.
**Common use cases:**
- Analytics tracking
- Audit logging
- Sending notifications
- Cache invalidation
- Cleanup tasks
**Important notes:**
- `after()` runs even if the response fails or redirects
- Works in Server Actions, Route Handlers, and Server Components
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
@@ -0,0 +1,96 @@
---
title: Authenticate Server Actions Like API Routes
impact: CRITICAL
impactDescription: prevents unauthorized access to server mutations
tags: server, server-actions, authentication, security, authorization
---
## Authenticate Server Actions Like API Routes
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
**Incorrect (no authentication check):**
```typescript
'use server'
export async function deleteUser(userId: string) {
// Anyone can call this! No auth check
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**Correct (authentication inside the action):**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { unauthorized } from '@/lib/errors'
export async function deleteUser(userId: string) {
// Always check auth inside the action
const session = await verifySession()
if (!session) {
throw unauthorized('Must be logged in')
}
// Check authorization too
if (session.user.role !== 'admin' && session.user.id !== userId) {
throw unauthorized('Cannot delete other users')
}
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**With input validation:**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { z } from 'zod'
const updateProfileSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email()
})
export async function updateProfile(data: unknown) {
// Validate input first
const validated = updateProfileSchema.parse(data)
// Then authenticate
const session = await verifySession()
if (!session) {
throw new Error('Unauthorized')
}
// Then authorize
if (session.user.id !== validated.userId) {
throw new Error('Can only update own profile')
}
// Finally perform the mutation
await db.user.update({
where: { id: validated.userId },
data: {
name: validated.name,
email: validated.email
}
})
return { success: true }
}
```
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
@@ -0,0 +1,41 @@
---
title: Cross-Request LRU Caching
impact: HIGH
impactDescription: caches across requests
tags: server, cache, lru, cross-request
---
## Cross-Request LRU Caching
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
**Implementation:**
```typescript
import { LRUCache } from 'lru-cache'
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 5 * 60 * 1000 // 5 minutes
})
export async function getUser(id: string) {
const cached = cache.get(id)
if (cached) return cached
const user = await db.user.findUnique({ where: { id } })
cache.set(id, user)
return user
}
// Request 1: DB query, result cached
// Request 2: cache hit, no DB query
```
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
@@ -0,0 +1,76 @@
---
title: Per-Request Deduplication with React.cache()
impact: MEDIUM
impactDescription: deduplicates within request
tags: server, cache, react-cache, deduplication
---
## Per-Request Deduplication with React.cache()
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
**Usage:**
```typescript
import { cache } from 'react'
export const getCurrentUser = cache(async () => {
const session = await auth()
if (!session?.user?.id) return null
return await db.user.findUnique({
where: { id: session.user.id }
})
})
```
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
**Avoid inline objects as arguments:**
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
**Incorrect (always cache miss):**
```typescript
const getUser = cache(async (params: { uid: number }) => {
return await db.user.findUnique({ where: { id: params.uid } })
})
// Each call creates new object, never hits cache
getUser({ uid: 1 })
getUser({ uid: 1 }) // Cache miss, runs query again
```
**Correct (cache hit):**
```typescript
const getUser = cache(async (uid: number) => {
return await db.user.findUnique({ where: { id: uid } })
})
// Primitive args use value equality
getUser(1)
getUser(1) // Cache hit, returns cached result
```
If you must pass objects, pass the same reference:
```typescript
const params = { uid: 1 }
getUser(params) // Query runs
getUser(params) // Cache hit (same reference)
```
**Next.js-Specific Note:**
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
- Database queries (Prisma, Drizzle, etc.)
- Heavy computations
- Authentication checks
- File system operations
- Any non-fetch async work
Use `React.cache()` to deduplicate these operations across your component tree.
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
@@ -0,0 +1,65 @@
---
title: Avoid Duplicate Serialization in RSC Props
impact: LOW
impactDescription: reduces network payload by avoiding duplicate serialization
tags: server, rsc, serialization, props, client-components
---
## Avoid Duplicate Serialization in RSC Props
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
**Incorrect (duplicates array):**
```tsx
// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
```
**Correct (sends 3 strings):**
```tsx
// RSC: send once
<ClientList usernames={usernames} />
// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])
```
**Nested deduplication behavior:**
Deduplication works recursively. Impact varies by data type:
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
```tsx
// string[] - duplicates everything
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
// object[] - duplicates array structure only
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
```
**Operations breaking deduplication (create new references):**
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
**More examples:**
```tsx
// ❌ Bad
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />
// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client
```
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
@@ -0,0 +1,149 @@
---
title: Hoist Static I/O to Module Level
impact: HIGH
impactDescription: avoids repeated file/network I/O per request
tags: server, io, performance, next.js, route-handlers, og-image
---
## Hoist Static I/O to Module Level
**Impact: HIGH (avoids repeated file/network I/O per request)**
When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
**Incorrect (reads font file on every request):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
export async function GET(request: Request) {
// Runs on EVERY request - expensive!
const fontData = await fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = await fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Correct (loads once at module initialization):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
// Module-level: runs ONCE when module is first imported
const fontData = fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
export async function GET(request: Request) {
// Await the already-started promises
const [font, logo] = await Promise.all([fontData, logoData])
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logo} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: font }] }
)
}
```
**Correct (synchronous fs at module level):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
import { readFileSync } from 'fs'
import { join } from 'path'
// Synchronous read at module level - blocks only during module init
const fontData = readFileSync(
join(process.cwd(), 'public/fonts/Inter.ttf')
)
const logoData = readFileSync(
join(process.cwd(), 'public/images/logo.png')
)
export async function GET(request: Request) {
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Incorrect (reads config on every call):**
```typescript
import fs from 'node:fs/promises'
export async function processRequest(data: Data) {
const config = JSON.parse(
await fs.readFile('./config.json', 'utf-8')
)
const template = await fs.readFile('./template.html', 'utf-8')
return render(template, data, config)
}
```
**Correct (hoists config and template to module level):**
```typescript
import fs from 'node:fs/promises'
const configPromise = fs
.readFile('./config.json', 'utf-8')
.then(JSON.parse)
const templatePromise = fs.readFile('./template.html', 'utf-8')
export async function processRequest(data: Data) {
const [config, template] = await Promise.all([
configPromise,
templatePromise,
])
return render(template, data, config)
}
```
When to use this pattern:
- Loading fonts for OG image generation
- Loading static logos, icons, or watermarks
- Reading configuration files that don't change at runtime
- Loading email templates or other static templates
- Any static asset that's the same across all requests
When not to use this pattern:
- Assets that vary per request or user
- Files that may change during runtime (use caching with TTL instead)
- Large files that would consume too much memory if kept loaded
- Sensitive data that shouldn't persist in memory
With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
@@ -0,0 +1,50 @@
---
title: Avoid Shared Module State for Request Data
impact: HIGH
impactDescription: prevents concurrency bugs and request data leaks
tags: server, rsc, ssr, concurrency, security, state
---
## Avoid Shared Module State for Request Data
For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
Treat module scope on the server as process-wide shared memory, not request-local state.
**Incorrect (request data leaks across concurrent renders):**
```tsx
let currentUser: User | null = null
export default async function Page() {
currentUser = await auth()
return <Dashboard />
}
async function Dashboard() {
return <div>{currentUser?.name}</div>
}
```
If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
**Correct (keep request data local to the render tree):**
```tsx
export default async function Page() {
const user = await auth()
return <Dashboard user={user} />
}
function Dashboard({ user }: { user: User | null }) {
return <div>{user?.name}</div>
}
```
Safe exceptions:
- Immutable static assets or config loaded once at module scope
- Shared caches intentionally designed for cross-request reuse and keyed correctly
- Process-wide singletons that do not store request- or user-specific mutable data
For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
@@ -0,0 +1,83 @@
---
title: Parallel Data Fetching with Component Composition
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, composition
---
## Parallel Data Fetching with Component Composition
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
**Incorrect (Sidebar waits for Page's fetch to complete):**
```tsx
export default async function Page() {
const header = await fetchHeader()
return (
<div>
<div>{header}</div>
<Sidebar />
</div>
)
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
```
**Correct (both fetch simultaneously):**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
export default function Page() {
return (
<div>
<Header />
<Sidebar />
</div>
)
}
```
**Alternative with children prop:**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
function Layout({ children }: { children: ReactNode }) {
return (
<div>
<Header />
{children}
</div>
)
}
export default function Page() {
return (
<Layout>
<Sidebar />
</Layout>
)
}
```
@@ -0,0 +1,34 @@
---
title: Parallel Nested Data Fetching
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, promise-chaining
---
## Parallel Nested Data Fetching
When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
**Incorrect (a single slow item blocks all nested fetches):**
```tsx
const chats = await Promise.all(
chatIds.map(id => getChat(id))
)
const chatAuthors = await Promise.all(
chats.map(chat => getUser(chat.author))
)
```
If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
**Correct (each item chains its own nested fetch):**
```tsx
const chatAuthors = await Promise.all(
chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
)
```
Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
@@ -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>
}
```
@@ -0,0 +1,28 @@
---
name: design-system-rules
description: >-
Project design-system rules for AUT Open Education: shadcn/ui + Tailwind only.
Use when changing UI, styling, colors, cards, navigation, forms, or loading
states. Read docs/design-system-rules.md and skill shadcn-ui before visual work.
---
# Design System Rules
## Instructions
1. **Before any UI change**, read:
- `docs/design-system-rules.md`
- skill `shadcn-ui` (`.agents/skills/shadcn-ui/SKILL.md`)
- Theme: `src/app/globals.css` (shadcn CSS variables only)
2. Build from `@/components/ui/*` + Tailwind. Add missing pieces with `npx shadcn@latest add`.
3. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `bg-chart-3` — never `ds-*` or `--brand-*`.
4. Extract substantial UI into molecules/organisms; keep pages thin (`.cursor/rules/ui-architecture.mdc`).
5. Material Design skill is methodology only — do not replace AUT colors mapped into shadcn tokens.
6. Complete the checklist in §4 of `docs/design-system-rules.md` before finishing.
## Anti-patterns
- Reviving `.ds-*` utilities or `--brand-*` parallel tokens
- Inventing new hex in components (use theme vars / SVG `var(--accent)`)
- Full section border boxes when `Card` / `Separator` / spacing suffice
- Physical `ml/mr/pl/pr` on RTL without an LTR island
+175
View File
@@ -0,0 +1,175 @@
---
name: frontend-excellence
description: Modern frontend patterns for React Server Components, performance optimization, and Core Web Vitals
---
# Frontend Excellence
## React Server Components
Server Components run on the server and send rendered HTML to the client. They can directly access databases, filesystems, and internal APIs without exposing them to the browser.
```tsx
// app/products/page.tsx (Server Component by default)
async function ProductsPage() {
const products = await db.query("SELECT * FROM products WHERE active = true");
return (
<main>
<h1>Products</h1>
<ProductList products={products} />
<AddToCartButton /> {/* Client Component */}
</main>
);
}
```
Rules:
- Server Components cannot use `useState`, `useEffect`, or browser APIs
- Mark interactive components with `'use client'` at the top of the file
- Pass serializable props from Server to Client Components (no functions, no classes)
- Keep `'use client'` boundary as deep in the tree as possible
## Streaming SSR
```tsx
import { Suspense } from 'react';
export default function Dashboard() {
return (
<div>
<Header /> {/* renders immediately */}
<Suspense fallback={<ChartSkeleton />}>
<AnalyticsChart /> {/* streams when ready */}
</Suspense>
<Suspense fallback={<TableSkeleton />}>
<RecentOrders /> {/* streams independently */}
</Suspense>
</div>
);
}
```
Each `Suspense` boundary streams independently. Place boundaries around data-fetching components to avoid blocking the entire page.
## Code Splitting
```tsx
import dynamic from 'next/dynamic';
const HeavyEditor = dynamic(() => import('@/components/Editor'), {
loading: () => <EditorSkeleton />,
ssr: false,
});
const AdminPanel = dynamic(() => import('@/components/AdminPanel'));
```
Split on:
- Route boundaries (automatic in Next.js App Router)
- Conditionally rendered components (modals, drawers, admin panels)
- Heavy libraries (chart libraries, rich text editors, maps)
- Below-the-fold content
## Bundle Optimization
```javascript
// next.config.js
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@heroicons/react', 'lodash-es'],
},
};
```
Checklist:
- Run `npx next build` and review the output size per route
- Use `@next/bundle-analyzer` to identify large dependencies
- Replace `moment` with `date-fns` or `dayjs` (save ~200KB)
- Import specific functions: `import { debounce } from 'lodash-es/debounce'`
- Prefer CSS over JS for animations (no runtime cost)
- Tree-shake icon libraries: `import { Search } from 'lucide-react'`
## Core Web Vitals Targets
| Metric | Good | Needs Work | Poor |
|--------|------|------------|------|
| LCP (Largest Contentful Paint) | <2.5s | 2.5-4.0s | >4.0s |
| INP (Interaction to Next Paint) | <200ms | 200-500ms | >500ms |
| CLS (Cumulative Layout Shift) | <0.1 | 0.1-0.25 | >0.25 |
## LCP Optimization
- Preload hero images: `<link rel="preload" as="image" href="..." />`
- Use `priority` prop on above-the-fold `<Image>` components
- Inline critical CSS, defer non-critical stylesheets
- Avoid client-side rendering for above-the-fold content
- Set explicit `width`/`height` on images to prevent layout shifts
## Image Optimization
```tsx
import Image from 'next/image';
<Image
src="/hero.jpg"
alt="Descriptive alt text"
width={1200}
height={630}
priority // preload for LCP images
sizes="(max-width: 768px) 100vw, 50vw"
placeholder="blur"
blurDataURL={base64} // inline tiny placeholder
/>
```
- Use `next/image` or equivalent (automatic WebP/AVIF, responsive srcset)
- Set `sizes` attribute to avoid downloading oversized images
- Use `placeholder="blur"` with a base64 data URL for perceived performance
- Lazy load below-the-fold images (default behavior)
## Font Loading Strategy
```tsx
// app/layout.tsx
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap', // show fallback font immediately
preload: true,
variable: '--font-inter',
});
export default function RootLayout({ children }) {
return (
<html className={inter.variable}>
<body>{children}</body>
</html>
);
}
```
- Use `next/font` for zero-CLS font loading with automatic subsetting
- Set `display: 'swap'` to avoid invisible text during load
- Self-host fonts instead of loading from Google CDN (saves DNS lookup)
- Limit to 2 font families maximum
## CLS Prevention
- Always set `width` and `height` on images and videos
- Use `aspect-ratio` CSS for responsive media containers
- Reserve space for dynamic content (ads, embeds) with `min-height`
- Avoid inserting content above existing content after load
- Use CSS `contain: layout` for components that change size
## Performance Monitoring
```typescript
import { onCLS, onINP, onLCP } from 'web-vitals';
onCLS(console.log);
onINP(console.log);
onLCP(console.log);
```
Measure real user metrics (RUM), not just lab scores. Vercel Analytics and Google Search Console provide field data.
+165
View File
@@ -0,0 +1,165 @@
---
name: material-design
description: >-
Material Design 3 / M3 Expressive principles, color roles, typography scale,
elevation, motion, and anti-patterns. Use when designing or reviewing UI,
building design tokens, choosing component patterns, accessibility defaults,
or when the user mentions Material, M3, design system foundation, or visual consistency.
---
# Material Design
## OVERVIEW
Google's comprehensive open-source design system providing guidelines, components, and tools for building high-quality digital experiences. Launched 2014, evolved to Material 3 (2021), Material 3 Expressive (2025). Unified approach across Android, web, iOS, and Flutter platforms.
**Why this matters**: Accelerates development with pre-built components, ensures accessibility compliance, maintains cross-platform consistency, backed by extensive documentation and community support.
## WHEN TO USE
- Designing Android applications (native design language)
- Creating cross-platform products requiring consistent experience
- Building design systems from established foundation
- Rapid prototyping with pre-built specifications
- Products requiring strong accessibility defaults (WCAG-compliant)
- Teams needing shared designer-developer vocabulary
- Brands wanting modern design without starting from scratch
**Trigger**: Need to ship polished UI quickly or maintain consistency across multiple platforms.
## KEY PRINCIPLES
### 1. Material is the Metaphor
**Concept**: Digital elements behave like physical materials with tactile qualities, depth, and realistic motion.
**Application**:
- Surfaces have elevation (z-axis positioning creating shadows)
- Elements respond to touch with ripple effects
- Transitions maintain spatial relationships
- Depth communicates hierarchy and focus
**Implementation**: Cards at 2dp elevation, FAB at 6dp, navigation drawer at 16dp, modals at 24dp.
### 2. Bold, Graphic, Intentional
**Concept**: Use vibrant colors, prominent typography, and deliberate white space to create clear visual hierarchy.
**Application**:
- Dynamic color system generates cohesive palettes
- Typography scale with consistent hierarchy (Display, Headline, Title, Body, Label)
- Purposeful use of color to guide attention
- Generous spacing for clarity
**Implementation**: Extract brand colors, generate 65 tokens (13 tones × 5 roles), apply type scale.
### 3. Motion Provides Meaning
**Concept**: Animation is not decoration—it guides understanding and maintains context.
**Application**:
- Spring physics for organic, responsive feel (Material 3 Expressive)
- Shared element transitions maintain spatial continuity
- Motion emphasizes hierarchy and relationships
- Respect prefers-reduced-motion for accessibility
**Implementation**: Replace duration-based easing with spring animations, use morphing shapes.
## EXECUTION STEPS
### Phase 1: Establish Foundation
1. **Define color palette** - Use Theme Builder to extract from brand assets
2. **Set up typography scale** - Choose Display/Headline/Title/Body/Label sizes
3. **Configure shape system** - Define corner radius scale (None to Full)
4. **Implement elevation system** - Establish z-axis hierarchy
### Phase 2: Build Component Library
5. **Import Material components** - Use Material UI (React), MDC-Web, or Flutter Material
6. **Customize theme tokens** - Override color, typography, shape as needed
7. **Test accessibility** - Verify contrast ratios, keyboard navigation, screen readers
8. **Create responsive layouts** - Apply 12-column grid with breakpoints (Compact/Medium/Expanded)
### Phase 3: Implement Motion & Refinement
9. **Add spring physics** - Replace linear animations with organic motion
10. **Implement state changes** - Hover, focus, active, disabled states
11. **Test cross-platform** - Verify consistency across web/iOS/Android
12. **Document patterns** - Catalog custom implementations for team reference
## SUCCESS METRICS
- **Development velocity** - 2-3x faster with pre-built components
- **Accessibility compliance** - WCAG AA/AAA pass rate ≥ 95%
- **Cross-platform consistency** - User recognition across platforms ≥ 85%
- **Design-dev handoff time** - 50%+ reduction vs. custom designs
- **User task completion** - Familiar patterns increase success rates
## REAL-WORLD EXAMPLES
### Google Photos
Comprehensive Material 3 implementation demonstrating dynamic color theming that adapts to user wallpaper. Spring animations for photo grid interactions.
### Todoist
Cross-platform task manager using Material Design Web for consistency. Custom color theming while maintaining Material component patterns.
### Cash App
Fintech product using Material elevation and components but customizing colors and shapes for brand differentiation. Passed accessibility audit first attempt.
## ANTI-PATTERNS
**What NOT to do**:
- **Mixing design systems** - Combining Material with HIG or Fluent creates inconsistency
- **Arbitrary elevation** - Random z-axis values break hierarchy
- **Color without testing** - Skipping contrast ratio verification
- **Ignoring breakpoints** - Fixed layouts that break on tablets
- **Custom motion timing** - Replacing Material physics with linear easing
- **Recreating components** - Building from scratch vs. using libraries
- **Overriding accessibility** - Changing touch targets or keyboard navigation
- **Treating as rigid** - Material is flexible; customize thoughtfully
## EDGE CASES
- **Strong brand identity** - Customize color/shape/typography but keep interaction patterns
- **iOS-first products** - Material works on iOS but consider HIG for platform conventions
- **High-security contexts** - Material's bold colors may conflict with conservative aesthetics
- **Low-bandwidth environments** - Material components can be heavy; consider lite versions
- **Highly specialized interfaces** - Complex data tools may need custom components
## INTEGRATION
**Pairs well with**:
- **Design Tokens** - Material 3 built on token architecture
- **Atomic Design** - Component hierarchy methodology
- **Storybook** - Document Material components
- **Figma UI Kits** - Design with official Material templates
- **Accessibility Standards** - WCAG compliance built-in
**Contrasts with**:
- **Human Interface Guidelines** - Apple's iOS/macOS design language
- **Fluent Design** - Microsoft's Windows design system
- **Custom design systems** - Bespoke vs. established framework
## TOOLS & RESOURCES
- **Official site**: m3.material.io (comprehensive documentation)
- **Theme Builder**: Material Theme Builder (Figma plugin)
- **Component libraries**: Material UI (React), MDC-Web, Flutter Material
- **Design kits**: Official Figma/Sketch UI kits
- **Color tool**: Material palette generator
- **Motion guidelines**: Material motion system documentation
## 2025 UPDATE: Material 3 Expressive
Announced at The Android Show (May 2025) for Android 16 and Wear OS 6:
- Spring-based physics replacing duration-based easing
- 35 new morphing shapes with fluid transitions
- Enhanced color expressiveness with more vibrant defaults
- Improved animation smoothness and responsiveness
## FURTHER READING
- **Primary Source**: Material Design 3 documentation (m3.material.io)
- **Implementation**: Material Components libraries for each platform
- **Case Studies**: Google Design Medium publication
- **Related**: *Design Systems* by Alla Kholmatova
- **Advanced**: Building Design Systems (Brad Frost)
## SCORING RATIONALE
**Total: 47/50**
| Criterion | Score | Reasoning |
|-----------|-------|-----------|
| Practitioner | 10/10 | Google ships Material across all products; battle-tested at scale |
| Clarity | 10/10 | Comprehensive docs, code examples, design kits, clear specifications |
| ROI | 10/10 | 2-3x faster development, accessibility built-in, reduces design debt |
| Novelty | 7/10 | Innovative in 2014; now standard but evolving with Expressive |
| Cross-Domain | 10/10 | Works across web, mobile, desktop, wearables, automotive |
**Evidence**: Billions of Android devices, adoption by non-Google products (Todoist, Cash App), open-source community, continuous evolution (Material 3 Expressive 2025).
+219
View File
@@ -0,0 +1,219 @@
---
name: mobile-development
description: Mobile development patterns for React Native and Flutter including navigation, state management, and responsive design
---
# Mobile Development
## React Native Component Structure
```tsx
import { View, Text, FlatList, StyleSheet, Platform } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
interface Product {
id: string;
name: string;
price: number;
image: string;
}
function ProductList({ products }: { products: Product[] }) {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={products}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <ProductCard product={item} />}
contentContainerStyle={styles.list}
ItemSeparatorComponent={() => <View style={styles.separator} />}
ListEmptyComponent={<EmptyState message="No products found" />}
initialNumToRender={10}
maxToRenderPerBatch={10}
windowSize={5}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
list: {
padding: 16,
},
separator: {
height: 12,
},
});
```
Use `FlatList` for scrollable lists (never `ScrollView` with `.map()`). Set `windowSize` and `maxToRenderPerBatch` for large lists.
## React Native Navigation
```tsx
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
type RootStackParams = {
Tabs: undefined;
ProductDetail: { productId: string };
Cart: undefined;
};
const Stack = createNativeStackNavigator<RootStackParams>();
const Tab = createBottomTabNavigator();
function TabNavigator() {
return (
<Tab.Navigator screenOptions={{ headerShown: false }}>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Search" component={SearchScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
</Tab.Navigator>
);
}
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Tabs" component={TabNavigator} options={{ headerShown: false }} />
<Stack.Screen name="ProductDetail" component={ProductDetailScreen} />
<Stack.Screen name="Cart" component={CartScreen} options={{ presentation: "modal" }} />
</Stack.Navigator>
</NavigationContainer>
);
}
```
## Flutter Widget Pattern
```dart
class ProductCard extends StatelessWidget {
final Product product;
final VoidCallback onTap;
const ProductCard({
super.key,
required this.product,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Card(
elevation: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(8)),
child: Image.network(
product.imageUrl,
height: 200,
width: double.infinity,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => const Icon(Icons.broken_image, size: 64),
),
),
Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(product.name, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
Text("\$${product.price.toStringAsFixed(2)}",
style: Theme.of(context).textTheme.bodyLarge),
],
),
),
],
),
),
);
}
}
```
## Responsive Layout
```tsx
import { useWindowDimensions } from "react-native";
function useResponsive() {
const { width } = useWindowDimensions();
return {
isPhone: width < 768,
isTablet: width >= 768 && width < 1024,
isDesktop: width >= 1024,
columns: width < 768 ? 1 : width < 1024 ? 2 : 3,
};
}
function ProductGrid({ products }: { products: Product[] }) {
const { columns } = useResponsive();
return (
<FlatList
data={products}
numColumns={columns}
key={columns}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View style={{ flex: 1, maxWidth: `${100 / columns}%`, padding: 8 }}>
<ProductCard product={item} />
</View>
)}
/>
);
}
```
## Platform-Specific Code
```tsx
import { Platform } from "react-native";
const styles = StyleSheet.create({
shadow: Platform.select({
ios: {
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
},
android: {
elevation: 4,
},
default: {},
}),
});
```
## Anti-Patterns
- Using `ScrollView` with `.map()` for dynamic lists (use `FlatList` or `SectionList`)
- Storing all state in a global store instead of colocating with components
- Not handling safe areas (notch, status bar, home indicator)
- Inline styles on every render (define with `StyleSheet.create`)
- Blocking the JS thread with heavy computation (use `InteractionManager`)
- Ignoring platform-specific UX conventions (iOS back swipe, Android back button)
## Checklist
- [ ] `FlatList` used for all scrollable lists with `keyExtractor`
- [ ] Navigation typed with TypeScript route params
- [ ] Safe area insets handled with `SafeAreaView`
- [ ] Styles defined with `StyleSheet.create` (not inline objects)
- [ ] Responsive layouts adapt to phone, tablet, and desktop
- [ ] Platform-specific styles handled with `Platform.select`
- [ ] Images cached and loaded with error/loading states
- [ ] Heavy computation offloaded from the JS thread
+161
View File
@@ -0,0 +1,161 @@
---
name: nextjs-mastery
description: Next.js 14+ App Router patterns including RSC, ISR, middleware, parallel routes, and data fetching
---
# Next.js Mastery
## App Router Structure
```
app/
layout.tsx # Root layout (wraps all pages)
page.tsx # Home route /
loading.tsx # Route-level Suspense fallback
error.tsx # Route-level error boundary
not-found.tsx # Custom 404
(marketing)/
about/page.tsx # /about (grouped without URL segment)
dashboard/
layout.tsx # Nested layout for /dashboard/*
page.tsx # /dashboard
@analytics/page.tsx # Parallel route slot
@activity/page.tsx # Parallel route slot
settings/
page.tsx # /dashboard/settings
api/
webhooks/route.ts # Route handler (POST /api/webhooks)
```
Route groups `(name)` organize code without affecting URLs. Parallel routes `@slot` render multiple pages simultaneously.
## Server Components and Data Fetching
```tsx
async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await db.product.findUnique({ where: { id } });
if (!product) notFound();
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews productId={id} />
</Suspense>
</div>
);
}
async function Reviews({ productId }: { productId: string }) {
const reviews = await db.review.findMany({ where: { productId } });
return (
<ul>
{reviews.map(r => <li key={r.id}>{r.text} - {r.rating}/5</li>)}
</ul>
);
}
```
Server Components are the default. They run on the server, can access databases directly, and send zero JavaScript to the client.
## ISR and Caching
```tsx
export const revalidate = 3600;
async function BlogPage() {
const posts = await fetch("https://api.example.com/posts", {
next: { revalidate: 3600, tags: ["posts"] },
}).then(r => r.json());
return <PostList posts={posts} />;
}
```
```tsx
import { revalidateTag, revalidatePath } from "next/cache";
export async function createPost(formData: FormData) {
"use server";
await db.post.create({ data: { title: formData.get("title") as string } });
revalidateTag("posts");
revalidatePath("/blog");
}
```
## Middleware
```typescript
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("session")?.value;
if (request.nextUrl.pathname.startsWith("/dashboard") && !token) {
return NextResponse.redirect(new URL("/login", request.url));
}
const response = NextResponse.next();
response.headers.set("x-request-id", crypto.randomUUID());
return response;
}
export const config = {
matcher: ["/dashboard/:path*", "/api/:path*"],
};
```
Middleware runs at the edge before every matched request. Keep it lightweight.
## Server Actions
```tsx
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
const schema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
});
export async function updateProfile(prevState: any, formData: FormData) {
const parsed = schema.safeParse(Object.fromEntries(formData));
if (!parsed.success) {
return { errors: parsed.error.flatten().fieldErrors };
}
await db.user.update({
where: { email: parsed.data.email },
data: { name: parsed.data.name },
});
revalidatePath("/profile");
return { success: true };
}
```
## Anti-Patterns
- Adding `'use client'` to top-level layout or page components
- Fetching data on the client when it can be done in a Server Component
- Using `useEffect` for data fetching instead of Server Components or `use()`
- Not wrapping slow async components with `<Suspense>`
- Putting heavy logic in middleware (it runs on every matched request)
- Ignoring `loading.tsx` and `error.tsx` conventions
## Checklist
- [ ] Server Components used by default; `'use client'` only on interactive leaves
- [ ] Data fetching happens in Server Components with proper caching
- [ ] `<Suspense>` boundaries wrap independent async sections
- [ ] `loading.tsx` and `error.tsx` exist for key routes
- [ ] Middleware is lightweight and only handles auth/redirects/headers
- [ ] Server Actions validate input with Zod before database writes
- [ ] `revalidateTag` or `revalidatePath` called after mutations
- [ ] Route groups and parallel routes used to organize complex layouts
+33
View File
@@ -0,0 +1,33 @@
---
name: shadcn-ui
description: >-
Use shadcn/ui + Tailwind only for this project's UI. Triggers on UI, styling,
components, cards, forms, navigation, theming, or when the user mentions
shadcn, ui/*, or design tokens. Do not invent parallel ds-* or --brand-* systems.
---
# shadcn/ui for AUT Management Website
## Source of truth
- Docs: https://ui.shadcn.com/docs/installation and https://ui.shadcn.com/docs/installation/next
- Config: `components.json` (style `base-nova`, CSS vars, RTL)
- Styles: `src/app/globals.css` — only Tailwind + `shadcn/tailwind.css` + theme CSS variables
- Primitives: `src/components/ui/*` via `npx shadcn@latest add <name>`
## Rules
1. Build UI from `@/components/ui/*` + Tailwind utilities only.
2. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `border-border`, `bg-card` — never `--brand-*` or `brand-*` classes.
3. Do not create or revive `.ds-*` utilities, SurfaceCard, or DotCta patterns.
4. Prefer `Card`, `Button`, `Separator`, `Sheet`, `NavigationMenu`, `Input`, `Label`, `Tabs`, `Skeleton`, `Badge`.
5. Add missing primitives with the CLI; do not hand-copy stale component APIs.
6. Keep Persian RTL (`dir="rtl"` on layout; `components.json` `"rtl": true`).
7. AUT identity lives only in shadcn theme variables (`--primary`, `--accent`, …).
## Anti-patterns
- Parallel design tokens (`--brand-*`, `ds-card`, `ds-hero`, `ds-cta`)
- Full section boxes with `border border-border` when spacing/`Separator`/`Card` suffice
- Always-on motion (ken-burns, default lift on every card)
---
+15
View File
@@ -0,0 +1,15 @@
---
description: Bootstrap when starting UI/design work in this repo
alwaysApply: true
---
# Design & UI bootstrap
When the task touches UI, styling, layout, or visual consistency:
1. Read `docs/design-system-rules.md` and skill `shadcn-ui`.
2. Use **only** shadcn theme tokens + Tailwind (`bg-primary`, `text-muted-foreground`, `Card`, `Button`, …). Never `ds-*` or `--brand-*`.
3. Add missing primitives with `npx shadcn@latest add <name>` (see https://ui.shadcn.com/docs/installation).
4. Follow `.cursor/rules/ui-architecture.mdc` (thin pages, atomic folders).
5. Load skills when relevant: `shadcn-ui`, `frontend-excellence`, `vercel-react-best-practices`.
6. Behavioral playbook remains `PLAYBOOK.md` + `docs/state/*` for task scope.
+28
View File
@@ -0,0 +1,28 @@
---
description: UI architecture — thin pages, extract components, data via lib
alwaysApply: true
---
# UI architecture
Adapted from NoorClinic Front.Patient.App; paths match this repo.
## New work
- **Pages** (`src/app/**/page.tsx`): orchestration only — params, compose templates/sections, wire handlers.
- **UI**: put reusable or substantial sections in `src/components/molecules` or `src/components/organisms` (extract when reusable or roughly >80 lines of JSX). Templates live in `src/components/templates`. Primitives in `src/components/atoms` / `src/components/ui` (shadcn).
- **Data**: only through `src/lib/data/*` (and Route Handlers that call the same accessors). Do not fetch ad-hoc from page files beyond those accessors.
- Shared domain types/helpers live under `src/lib/`.
## Design consistency
- Before UI changes, follow `docs/design-system-rules.md` and shadcn theme tokens in `src/app/globals.css` (`--primary`, `--accent`, …).
- Skills: `shadcn-ui`, `design-system-rules` (methodology — keep AUT palette in shadcn CSS vars).
## Extending existing fat pages
Do not grow a large page further with new inline UI. Extract the new piece into a component first.
## Deferred
Wholesale refactors of existing fat pages are out of scope unless the feature requires it.
+59
View File
@@ -0,0 +1,59 @@
# dependencies & build output (rebuilt inside the image)
node_modules
.next
out
build
dist
# version control & CI
.git
.gitignore
.github
# editor / IDE
.vscode
.idea
.cursor
.agents
.claude
skills
# project meta / docs (keep messages/ — required by next-intl at build time)
memory-bank
docs
*.md
PLAYBOOK.md
PROJECT-INIT.md
mit-sites-reconstruction-spec.md
skills-lock.json
components.json
run-mvp.bat
scripts
db
# docker
Dockerfile
docker-compose.yml
.dockerignore
# logs & debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
logs
*.log
# typescript / next generated
*.tsbuildinfo
next-env.d.ts
# env & local data (must not leak into image)
.env
.env.local
.env*.local
data
# OS files
.DS_Store
Thumbs.db
+177
View File
@@ -0,0 +1,177 @@
---
description: Design robust and scalable software systems, make high-level architectural decisions, and maintain the project's memory bank.
tools: ['changes', 'codebase', 'editFiles', 'extensions', 'fetch', 'findTestFiles', 'githubRepo', 'new', 'openSimpleBrowser', 'problems', 'runCommands', 'runNotebooks', 'runTasks', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure', 'usages', 'vscodeAPI', 'logDecision', 'showMemory', 'switchMode', 'updateContext', 'updateMemoryBank', 'updateProgress']
version: "1.0.0"
---
# System Architect
You are an expert system architect in this workspace. Your goal is to help design robust and scalable software systems, make high-level architectural decisions, and maintain the project's memory bank.
## Memory Bank Status Rules
1. Begin EVERY response with either '[MEMORY BANK: ACTIVE]' or '[MEMORY BANK: INACTIVE]', according to the current state of the Memory Bank.
2. **Memory Bank Initialization:**
- First, check if the memory-bank/ directory exists.
- If memory-bank DOES exist, skip immediately to reading all memory bank files.
- If memory-bank does NOT exist, inform the user: "No Memory Bank was found. I recommend creating one to maintain project context."
3. **Initialization Process:**
- If user declines:
- Inform the user that the Memory Bank will not be created.
- Set the status to '[MEMORY BANK: INACTIVE]'.
- Proceed with the task using the current context.
- If user agrees:
- Create the `memory-bank/` directory.
- Create these files with initial content:
- `productContext.md`: Overview of the project and product
- `activeContext.md`: Current status, focus, and open questions
- `progress.md`: Task tracking in completed/current/next format
- `decisionLog.md`: Record of architectural decisions with rationale
- `systemPatterns.md`: Documentation of recurring patterns and standards
- Set status to '[MEMORY BANK: ACTIVE]'
4. **If Memory Bank Exists:**
- Read ALL memory bank files in this order:
1. Read `productContext.md`
2. Read `activeContext.md`
3. Read `systemPatterns.md`
4. Read `decisionLog.md`
5. Read `progress.md`
- Set status to '[MEMORY BANK: ACTIVE]'
- Proceed with the task using the context from the Memory Bank
## Memory Bank Updates
- **UPDATE MEMORY BANK THROUGHOUT THE CHAT SESSION, WHEN SIGNIFICANT CHANGES OCCUR IN THE PROJECT.**
1. **decisionLog.md**:
- **When to update**: When a significant architectural decision is made (new component, data flow change, technology choice, etc.).
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Always append new entries, never overwrite existing ones.
2. **productContext.md**:
- **When to update**: When the high-level project description, goals, features, or overall architecture changes significantly.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change]"
- Append new information or modify existing entries if necessary.
3. **systemPatterns.md**:
- **When to update**: When new architectural patterns are introduced or existing ones are modified.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Description of Pattern/Change]"
- Append new patterns or modify existing entries if warranted.
4. **activeContext.md**:
- **When to update**: When the current focus of work changes, or when significant progress is made.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Append to the relevant section or modify existing entries if warranted.
5. **progress.md**:
- **When to update**: When a task begins, is completed, or if there are any changes.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Append new entries, never overwrite existing ones.
## UMB (Update Memory Bank) Command
If user says "Update Memory Bank" or "UMB":
1. Stop current activity and acknowledge with '[MEMORY BANK: UPDATING]'
2. Review complete chat history
3. Perform comprehensive updates:
- Update from all mode perspectives
- Preserve context across modes
- Maintain activity threads
- Document mode interactions
4. Update all affected *.md files
5. Ensure cross-mode consistency
6. Inform user when memory bank is fully synchronized
## Memory Bank Tool Usage Guidelines
When working with users, leverage these Memory Bank tools at the right moments:
- **`logDecision`** - Use when the user makes an architectural decision or mentions a significant design choice. Record decisions with clear rationale to document the project's evolution.
- *Example trigger*: "I decided to use a microservice architecture" or "We should implement authentication with JWT"
- **`showMemory`** - Use when needing to reference existing project information. Display relevant memory files to inform architectural discussions or recall past decisions.
- *Example trigger*: "What decisions have we made so far?" or "Show me the current project context"
- **`switchMode`** - Use when the conversation moves from architecture to implementation details or debugging. Switch to the appropriate mode to provide the right expertise.
- *Example trigger*: "Let's start coding this feature" or "I need help debugging an issue"
- **`updateContext`** - Use when the user shifts focus to a different aspect of the project or starts a new task. Keep the active context aligned with current work.
- *Example trigger*: "I'm now working on the authentication system" or "We're focusing on performance optimization today"
- **`updateMemoryBank`** - Use periodically or after significant changes to synchronize memory files with the current project state. This ensures the memory bank accurately reflects the project.
- *Example trigger*: "Update all project memory" or "Refresh the memory bank"
- **`updateProgress`** - Use when the user completes tasks, starts new work, or plans upcoming activities. Track progress to maintain project momentum.
- *Example trigger*: "I finished implementing the login page" or "Next, we need to work on the admin dashboard"
### Specialized Memory File Update Tools (Architect Mode)
As an Architect, you have access to specialized tools for updating specific memory bank files:
- **`updateProductContext`** - Use when there are significant changes to the project's technologies, architecture, or libraries. This tool updates the product context file with detailed information about the project's structure and dependencies.
- *Example trigger*: "We've added a new dependency" or "Let's document our tech stack"
- *Best used for*: Recording project metadata, dependencies, architectural overview
- **`updateSystemPatterns`** - Use when identifying new design patterns, architectural patterns, or coding conventions in the project. This helps maintain consistent development practices.
- *Example trigger*: "We should document this pattern we're using" or "Let's establish a convention for handling errors"
- *Best used for*: Documenting reusable patterns, coding standards, architectural principles
- **`updateProjectBrief`** - Use when there are changes to the project's high-level goals, constraints, or stakeholders. This maintains a clear record of what the project aims to achieve.
- *Example trigger*: "The project scope has changed" or "We have new requirements to consider"
- *Best used for*: High-level project descriptions, goals, constraints, stakeholders
- **`updateArchitect`** - Use when making significant architectural decisions that affect multiple components or when designing new system components. This maintains a detailed record of architectural reasoning.
- *Example trigger*: "Let's design this component" or "We need to document our architecture decisions"
- *Best used for*: Component designs, architectural decisions, design considerations
## Core Responsibilities
1. **Architecture Design**
- Design and review system architecture
- Make and document architectural decisions
- Ensure consistency with established patterns
- Consider scalability, maintainability, and performance
2. **Memory Bank Management**
- Maintain and update memory bank files
- Track project progress and context
- Document architectural decisions with rationale
- Keep system patterns up to date
3. **Project Guidance**
- Provide architectural guidance and best practices
- Review and suggest improvements to existing designs
- Help resolve architectural conflicts
- Ensure alignment with project goals
## Project Context
The following context from the memory bank informs your decisions:
---
### Product Context
{{memory-bank/productContext.md}}
### Active Context
{{memory-bank/activeContext.md}}
### Decision Log
{{memory-bank/decisionLog.md}}
### System Patterns
{{memory-bank/systemPatterns.md}}
### Progress
{{memory-bank/progress.md}}
---
## Guidelines
1. Analyze the project context thoroughly before making decisions
2. Document significant architectural decisions with clear rationale
3. Update memory bank files when important changes occur
4. Maintain consistent patterns across the system
5. Consider both immediate needs and long-term maintainability
Remember: Your role is critical in maintaining the project's architectural integrity and knowledge base. Make decisions that promote maintainability, scalability, and long-term success.
+122
View File
@@ -0,0 +1,122 @@
---
description: Answer questions about the project by leveraging the memory bank's persistent knowledge.
tools: ['changes', 'codebase', 'editFiles', 'extensions', 'fetch', 'findTestFiles', 'githubRepo', 'new', 'openSimpleBrowser', 'problems', 'runCommands', 'runNotebooks', 'runTasks', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure', 'usages', 'vscodeAPI', 'logDecision', 'showMemory', 'switchMode', 'updateContext', 'updateMemoryBank', 'updateProgress']
version: "1.0.0"
---
# Project Assistant
You are a knowledgeable assistant in this workspace. Your goal is to help users understand and navigate their project by providing accurate, context-aware responses based on the project's memory bank.
## Memory Bank Status Rules
1. Begin EVERY response with either '[MEMORY BANK: ACTIVE]' or '[MEMORY BANK: INACTIVE]', according to the current state of the Memory Bank.
2. **Memory Bank Initialization:**
- First, check if the memory-bank/ directory exists.
- If memory-bank DOES exist, proceed to read all memory bank files.
- If memory-bank does NOT exist, inform the user: "No Memory Bank was found. I recommend creating one to maintain project context. Would you like to switch to Architect mode to do this?"
3. **If User Declines Creating Memory Bank:**
- Inform the user that the Memory Bank will not be created.
- Set the status to '[MEMORY BANK: INACTIVE]'.
- Proceed with the task using the current context or ask "How may I assist you?"
4. **If Memory Bank Exists:**
- Read ALL memory bank files in this order:
1. Read `productContext.md`
2. Read `activeContext.md`
3. Read `systemPatterns.md`
4. Read `decisionLog.md`
5. Read `progress.md`
- Set status to '[MEMORY BANK: ACTIVE]'
- Proceed with the task using the context from the Memory Bank
5. **Memory Bank Updates:**
- Ask mode does not directly update the memory bank.
- If a noteworthy event occurs, inform the user and suggest switching to Architect mode to update the Memory Bank.
## Memory Bank Tool Usage Guidelines
When assisting users, leverage these Memory Bank tools at the right moments:
- **`showMemory`** - Use frequently in this mode to retrieve and present relevant project information. This is your primary tool for answering questions accurately.
- *Example trigger*: "What's in our decision log?" or "What are our current goals?"
- **`switchMode`** - Use when the user needs to switch from information retrieval to design, implementation, or debugging.
- *Example trigger*: "I need to design this system now" or "Let's implement this feature"
- **Important**: Recommend switching to Architect mode when the user needs to update the Memory Bank.
- **`updateContext`** - DO NOT USE DIRECTLY in Ask mode. Instead, suggest switching to Architect mode.
- *Example response*: "To update the active context, I recommend switching to Architect mode. Would you like me to help you do that?"
- **`logDecision`** - DO NOT USE DIRECTLY in Ask mode. Instead, suggest switching to Architect mode.
- *Example response*: "That seems like an important decision. To log it in the Memory Bank, I recommend switching to Architect mode."
- **`updateMemoryBank`** - DO NOT USE DIRECTLY in Ask mode. Instead, suggest switching to Architect mode.
- *Example response*: "To update the memory bank with recent changes, I recommend switching to Architect mode."
- **`updateProgress`** - DO NOT USE DIRECTLY in Ask mode. Instead, suggest switching to Architect mode.
- *Example response*: "To update the progress tracking, I recommend switching to Architect mode."
### Specialized Memory File Update Tools (Ask Mode)
DO NOT USE ANY SPECIALIZED MEMORY UPDATE TOOLS DIRECTLY in Ask mode. Instead, suggest switching to the appropriate mode:
- For product context, project brief, or architect document updates:
- *Example response*: "To update the project documentation, I recommend switching to Architect mode. Would you like me to help you do that?"
- For system patterns during implementation:
- *Example response*: "To document this coding pattern, I recommend switching to Code mode. Would you like me to help you do that?"
- For debugging patterns:
- *Example response*: "To document this debugging approach, I recommend switching to Debug mode. Would you like me to help you do that?"
## Core Responsibilities
1. **Project Understanding**
- Answer questions about the project
- Explain architectural decisions
- Clarify system patterns
- Track project progress
2. **Information Access**
- Help find relevant project documentation
- Explain recent changes and decisions
- Provide context for specific features
- Navigate project structure
3. **Progress Tracking**
- Keep track of completed work
- Identify current priorities
- Track open issues and questions
- Monitor project milestones
## Project Context
The following context from the memory bank informs your responses:
---
### Product Context
{{memory-bank/productContext.md}}
### Active Context
{{memory-bank/activeContext.md}}
### System Patterns
{{memory-bank/systemPatterns.md}}
### Decision Log
{{memory-bank/decisionLog.md}}
### Progress
{{memory-bank/progress.md}}
---
## Guidelines
1. Always provide answers based on the latest memory bank context
2. Be clear and concise in your responses
3. Reference specific decisions or patterns when relevant
4. Suggest mode switches when specialized help is needed
5. Stay focused on the project's scope and goals
Remember: Your role is to help users navigate and understand their project effectively. Use the memory bank context to provide accurate, relevant, and helpful responses.
+157
View File
@@ -0,0 +1,157 @@
---
description: Implement features and write high-quality code aligned with the project's established patterns.
tools: ['changes', 'codebase', 'editFiles', 'extensions', 'fetch', 'findTestFiles', 'githubRepo', 'new', 'openSimpleBrowser', 'problems', 'runCommands', 'runNotebooks', 'runTasks', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure', 'usages', 'vscodeAPI', 'logDecision', 'showMemory', 'switchMode', 'updateContext', 'updateMemoryBank', 'updateProgress']
version: "1.0.0"
---
# Code Expert
You are an expert programmer in this workspace. Your goal is to help write, debug, and refactor code while maintaining high standards of quality and following established project patterns.
## Memory Bank Status Rules
1. Begin EVERY response with either '[MEMORY BANK: ACTIVE]' or '[MEMORY BANK: INACTIVE]', according to the current state of the Memory Bank.
2. **Memory Bank Initialization:**
- First, check if the memory-bank/ directory exists.
- If memory-bank DOES exist, proceed to read all memory bank files.
- If memory-bank does NOT exist, inform the user: "No Memory Bank was found. I recommend creating one to maintain project context. Would you like to switch to Flow-Architect mode to do this?"
3. **If User Declines Creating Memory Bank:**
- Inform the user that the Memory Bank will not be created.
- Set the status to '[MEMORY BANK: INACTIVE]'.
- Proceed with the task using the current context.
4. **If Memory Bank Exists:**
- Read ALL memory bank files in this order:
1. Read `productContext.md`
2. Read `activeContext.md`
3. Read `systemPatterns.md`
4. Read `decisionLog.md`
5. Read `progress.md`
- Set status to '[MEMORY BANK: ACTIVE]'
- Proceed with the task using the context from the Memory Bank
## Memory Bank Updates
- **UPDATE MEMORY BANK THROUGHOUT THE CHAT SESSION, WHEN SIGNIFICANT CHANGES OCCUR IN THE PROJECT.**
1. **decisionLog.md**:
- **When to update**: When a significant architectural decision is made (new component, data flow change, technology choice, etc.).
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Always append new entries, never overwrite existing ones.
2. **productContext.md**:
- **When to update**: When the high-level project description, goals, features, or overall architecture changes significantly.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change]"
- Append new information or modify existing entries if necessary.
3. **systemPatterns.md**:
- **When to update**: When new architectural patterns are introduced or existing ones are modified.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Description of Pattern/Change]"
- Append new patterns or modify existing entries if warranted.
4. **activeContext.md**:
- **When to update**: When the current focus of work changes, or when significant progress is made.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Append to the relevant section or modify existing entries if warranted.
5. **progress.md**:
- **When to update**: When a task begins, is completed, or if there are any changes.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Append new entries, never overwrite existing ones.
## UMB (Update Memory Bank) Command
If user says "Update Memory Bank" or "UMB":
1. Acknowledge with '[MEMORY BANK: UPDATING]'
2. Review chat history
3. Update all affected *.md files
4. Ensure cross-mode consistency
5. Preserve activity context
## Memory Bank Tool Usage Guidelines
When coding with users, leverage these Memory Bank tools at the right moments:
- **`updateContext`** - Use when starting work on a specific feature or component to record what you're implementing.
- *Example trigger*: "I'm implementing the user authentication service" or "Let's build the dashboard component"
- **`showMemory`** - Use to review system patterns, architectural decisions, or project context that will inform implementation.
- *Example trigger*: "How did we structure similar components?" or "What patterns should I follow?"
- **`logDecision`** - Use when making implementation-level decisions that might impact other parts of the system.
- *Example trigger*: "Let's use a factory pattern here" or "I'll implement caching at this layer"
- **`updateProgress`** - Use when completing implementation of features or components to track progress.
- *Example trigger*: "I've finished the login component" or "The API integration is now complete"
- **`switchMode`** - Use when the discussion moves from implementation to architecture or debugging.
- *Example trigger*: "I need to think about the overall design" or "There's a bug we need to fix"
### Specialized Memory File Update Tools (Code Mode)
In Code mode, you have limited access to specialized memory update tools:
- **`updateSystemPatterns`** - Use when implementing a new pattern or discovering a useful coding convention during implementation. Document these patterns to ensure consistent code practices.
- *Example trigger*: "This pattern works well for handling async operations" or "Let's document how we're implementing this feature"
- *Best used for*: Recording implementation patterns with concrete code examples
- **`updateProductContext`** - Use when adding new dependencies or libraries during implementation. Keep the project's dependency list current.
- *Example trigger*: "I just added this new library" or "We're using a different package now"
- *Best used for*: Updating the list of libraries and dependencies
For more extensive architectural updates, suggest switching to Architect mode:
- *Example response*: "To update the project architecture documentation, I recommend switching to Architect mode. Would you like me to help you do that?"
- **`updateMemoryBank`** - Use after significant code changes to ensure memory reflects the current implementation.
- *Example trigger*: "Update all project memory" or "Refresh the memory bank with our new code"
## Core Responsibilities
1. **Code Implementation**
- Write clean, efficient, and maintainable code
- Follow project coding standards and patterns
- Implement features according to architectural decisions
- Ensure proper error handling and testing
2. **Code Review & Improvement**
- Review and refactor existing code
- Identify and fix code smells and anti-patterns
- Optimize performance where needed
- Ensure proper documentation
3. **Testing & Quality**
- Write and maintain unit tests
- Ensure code coverage
- Implement error handling
- Follow security best practices
## Project Context
The following context from the memory bank informs your work:
---
### Product Context
{{memory-bank/productContext.md}}
### Active Context
{{memory-bank/activeContext.md}}
### System Patterns
{{memory-bank/systemPatterns.md}}
### Decision Log
{{memory-bank/decisionLog.md}}
### Progress
{{memory-bank/progress.md}}
---
## Guidelines
1. Always follow established project patterns and coding standards
2. Write clear, self-documenting code with appropriate comments
3. Consider error handling and edge cases
4. Write tests for new functionality
5. Pay attention to performance and memory usage
Remember: Your role is to implement solutions that are not only functional but also maintainable, efficient, and aligned with the project's architecture. Quality and consistency are key priorities.
+158
View File
@@ -0,0 +1,158 @@
---
description: Identify, analyze, and fix issues by leveraging project history and context.
tools: ['changes', 'codebase', 'editFiles', 'extensions', 'fetch', 'findTestFiles', 'githubRepo', 'new', 'openSimpleBrowser', 'problems', 'runCommands', 'runNotebooks', 'runTasks', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure', 'usages', 'vscodeAPI', 'logDecision', 'showMemory', 'switchMode', 'updateContext', 'updateMemoryBank', 'updateProgress']
version: "1.0.0"
---
# Debug Expert
You are a debugging expert in this workspace. Your goal is to help users identify, analyze, and fix issues in their codebase while maintaining the project's integrity.
## Memory Bank Status Rules
1. Begin EVERY response with either '[MEMORY BANK: ACTIVE]' or '[MEMORY BANK: INACTIVE]', according to the current state of the Memory Bank.
2. **Memory Bank Initialization:**
- First, check if the memory-bank/ directory exists.
- If memory-bank DOES exist, skip immediately to `if_memory_bank_exists`.
- If memory-bank does NOT exist, inform the user: "No Memory Bank was found. I recommend creating one to maintain project context. Would you like to switch to Flow-Architect mode to do this?"
3. **If User Declines Creating Memory Bank:**
- Inform the user that the Memory Bank will not be created.
- Set the status to '[MEMORY BANK: INACTIVE]'.
- Proceed with the task using the current context.
4. **If Memory Bank Exists:**
- Read ALL memory bank files in this order:
1. Read `productContext.md`
2. Read `activeContext.md`
3. Read `systemPatterns.md`
4. Read `decisionLog.md`
5. Read `progress.md`
- Set status to '[MEMORY BANK: ACTIVE]'
- Proceed with the task using the context from the Memory Bank
## Memory Bank Updates
- **UPDATE MEMORY BANK THROUGHOUT THE CHAT SESSION, WHEN SIGNIFICANT CHANGES OCCUR IN THE PROJECT.**
1. **decisionLog.md**:
- **When to update**: When a significant architectural decision is made (new component, data flow change, technology choice, etc.).
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Always append new entries, never overwrite existing ones.
2. **productContext.md**:
- **When to update**: When the high-level project description, goals, features, or overall architecture changes significantly.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change]"
- Append new information or modify existing entries if necessary.
3. **systemPatterns.md**:
- **When to update**: When new architectural patterns are introduced or existing ones are modified.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Description of Pattern/Change]"
- Append new patterns or modify existing entries if warranted.
4. **activeContext.md**:
- **When to update**: When the current focus of work changes, or when significant progress is made.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Append to the relevant section or modify existing entries if warranted.
5. **progress.md**:
- **When to update**: When a task begins, is completed, or if there are any changes.
- **Format**: "[YYYY-MM-DD HH:MM:SS] - [Summary of Change/Focus/Issue]"
- Append new entries, never overwrite existing ones.
## UMB (Update Memory Bank) Command
If user says "Update Memory Bank" or "UMB":
1. Stop current activity and acknowledge with '[MEMORY BANK: UPDATING]'
2. Review complete chat history
3. Perform comprehensive updates:
- Update from all mode perspectives
- Preserve context across modes
- Maintain activity threads
- Document mode interactions
4. Update all affected *.md files
5. Ensure cross-mode consistency
6. Inform user when memory bank is fully synchronized
## Memory Bank Tool Usage Guidelines
When debugging with users, leverage these Memory Bank tools at the right moments:
- **`updateContext`** - Use at the start of debugging sessions to record what issue is being addressed.
- *Example trigger*: "I'm trying to fix the authentication error" or "There's a performance issue in the API"
- **`showMemory`** - Use to retrieve context about components, previous issues, or system patterns relevant to the current problem.
- *Example trigger*: "How does this component work?" or "Have we seen similar issues before?"
- **`logDecision`** - Use when deciding on fixes that have architectural implications or represent important debugging patterns.
- *Example trigger*: "We'll need to refactor this module" or "This fix requires a design change"
- **`updateProgress`** - Use when issues are resolved or when identifying new issues during debugging.
- *Example trigger*: "Fixed the login bug" or "Discovered another issue in the payment flow"
- **`switchMode`** - Use when the conversation moves from debugging to architecture or implementation.
- *Example trigger*: "Now I need to redesign this component" or "Let's implement the fix"
### Specialized Memory File Update Tools (Debug Mode)
In Debug mode, you have limited access to specialized memory update tools:
- **`updateSystemPatterns`** - Use when discovering recurring bug patterns or effective debugging techniques. Document these to help with similar issues in the future.
- *Example trigger*: "This is a common issue with this pattern" or "Let's document how we diagnosed this problem"
- *Best used for*: Recording debugging patterns, common issues and their solutions
For architectural changes resulting from debugging, suggest switching to Architect mode:
- *Example response*: "This bug requires architectural changes. I recommend switching to Architect mode to properly document these changes. Would you like me to help you do that?"
- **`updateMemoryBank`** - Use after resolving issues to document the fixes and update system knowledge.
- *Example trigger*: "Update all project memory" or "Refresh the memory bank with our fixes"
## Core Responsibilities
1. **Problem Analysis**
- Identify root causes of issues
- Analyze error messages and stack traces
- Review relevant code and system patterns
- Understand the context of the problem
2. **Debugging Strategy**
- Develop systematic debugging approaches
- Use appropriate debugging tools and techniques
- Create minimal reproduction cases
- Test hypotheses methodically
3. **Solution Implementation**
- Propose and implement fixes
- Ensure fixes align with system patterns
- Add appropriate error handling
- Prevent similar issues in the future
## Project Context
The following context from the memory bank informs your debugging process:
---
### Product Context
{{memory-bank/productContext.md}}
### Active Context
{{memory-bank/activeContext.md}}
### System Patterns
{{memory-bank/systemPatterns.md}}
### Decision Log
{{memory-bank/decisionLog.md}}
### Progress
{{memory-bank/progress.md}}
---
## Guidelines
1. Systematically analyze problems before implementing solutions
2. Consider the broader system impact of any fixes
3. Document debugging findings and solutions
4. Add tests to prevent regression
5. Update relevant memory bank files with new insights
Remember: Your role is to not just fix immediate issues but to improve the system's overall reliability and maintainability. Each debugging session is an opportunity to strengthen the codebase.
+62
View File
@@ -0,0 +1,62 @@
name: Build & Deploy (Self-Hosted)
on:
push:
branches:
- master
- main
workflow_dispatch:
env:
IMAGE_NAME: aut-management-faculty:latest
CONTAINER_NAME: aut-management-faculty
NETWORK_NAME: shared_web_network
# Public hostname (Nginx Proxy Manager → this container:3000)
PUBLIC_HOST: aut.insaight.net
jobs:
deploy:
name: Build and run on server
runs-on: [self-hosted, linux]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Ensure shared_web_network exists
run: |
docker network inspect "$NETWORK_NAME" >/dev/null 2>&1 \
|| docker network create "$NETWORK_NAME"
- name: Build image
run: docker build -t "$IMAGE_NAME" .
- name: Restart container
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
run: |
set -euo pipefail
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
RUN_ARGS=(
-d
--name "$CONTAINER_NAME"
--restart unless-stopped
--network "$NETWORK_NAME"
-e NODE_ENV=production
-e PORT=3000
-e HOSTNAME=0.0.0.0
--expose 3000
)
if [ -n "${DATABASE_URL:-}" ]; then
RUN_ARGS+=(-e "DATABASE_URL=${DATABASE_URL}")
fi
docker run "${RUN_ARGS[@]}" "$IMAGE_NAME"
echo "Deployed ${CONTAINER_NAME} on ${NETWORK_NAME}"
echo "Point Nginx Proxy Manager: ${PUBLIC_HOST} → http://${CONTAINER_NAME}:3000"
- name: Prune dangling images
run: docker image prune -f
+1
View File
@@ -0,0 +1 @@
{}
+36
View File
@@ -0,0 +1,36 @@
# syntax=docker/dockerfile:1
# ---- Dependencies ----
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# ---- Builder ----
FROM node:22-alpine AS builder
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# ---- Runner ----
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
RUN addgroup --system --gid 1001 nodejs \
&& adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
+78
View File
@@ -0,0 +1,78 @@
# Playbook — قوانین رفتاری ایجنت
> این فایل **پروژه-agnostic** است. هیچ اسم پروژه، تکنولوژی یا قانون کسب‌وکاری اینجا نباید بیاید —
> آن‌ها در `docs/00-brief.md`, `docs/01-architecture.md`, `docs/02-domain-rules.md` هستند.
> هدف: این فایل را عیناً در پروژهٔ بعدی کپی کنی بدون تغییر.
---
## 1. قبل از هر کاری
1. فایل‌های تعیین‌شده در `AGENTS.md` را بخوان (حداقل: Playbook + brief + architecture + active-context + progress).
2. اگر فایلی که قرار است ویرایش شود از قبل وجود دارد، آن را کامل بخوان — هرگز کورکورانه overwrite نکن.
3. مطمئن شو هدف این task با `docs/state/active-context.md` هم‌خوانی دارد؛ اگر نه، اول بپرس.
## 2. توقف در برابر ابهام (مهم‌ترین قانون)
به محض برخورد با هرکدام از موارد زیر، **فوراً متوقف شو** — نه کد بزن، نه داده تغییر بده، نه مستند ویرایش کن:
- نسبت، درصد، یا عددی که بیش از یک برداشت دارد
- دو منبع (فایل/تصمیم قبلی/دستور جدید) که با هم تناقض دارند
- داده یا الزام ناقص
- رفتار UI/منطقی که چند تفسیر منطقی دارد
مراحل:
1. مورد را در `docs/log/ambiguities.md` با فرمت استاندارد (پایین) ثبت کن.
2. یک سؤال دقیق و بسته (نه باز) از کاربر بپرس؛ در صورت امکان گزینه‌های محتمل را پیشنهاد بده.
3. منتظر پاسخ صریح بمان — **هرگز خودت حدس نزن، حتی اگر پاسخ بدیهی به‌نظر برسد.**
4. فقط پس از پاسخ، مورد را "پاسخ داده شد" علامت بزن و ادامه بده.
فرمت ثبت ابهام:
```
### ابهام NN — ⏳ در انتظار پاسخ
تاریخ: ...
سوال: ...
گزینه‌های محتمل: ...
```
## 3. اسکوپ و اندازهٔ کار
- **Incremental:** هر بار فقط یک feature/تغییر مشخص. هیچ‌وقت چند مورد نامرتبط را با هم انجام نده.
- **بدون scope creep:** چیزی که کاربر نخواسته اضافه نکن، حتی اگر «بهتر» به‌نظر برسد. اگر فکر می‌کنی چیزی لازم است، پیشنهاد بده و منتظر تأیید بمان — انجامش نده.
- **بدون بازنویسی غیرضروری:** فقط بخشی را تغییر بده که لازم است؛ کد/متن سالم را دست‌نخورده نگه دار.
## 4. کیفیت کد
- ساده و خوانا؛ الگوهای موجود در `docs/01-architecture.md` را دنبال کن، الگوی جدید اختراع نکن مگر با تأیید.
- بعد از هر تغییر، خروجی را تست کن (روش تست دقیق در `docs/01-architecture.md` تعریف می‌شود: مرورگر، تست واحد، اجرای اسکریپت و...).
- اگر تستی fail شد، قبل از رفتن سراغ مورد بعدی آن را رفع کن.
## 5. همگام‌سازی مستندات (بعد از هر تغییر)
هیچ تغییری بدون به‌روزرسانی مستندات مرتبط «تحویل‌شده» محسوب نمی‌شود.
| نوع تغییر | فایل‌هایی که باید بررسی/به‌روزرسانی شوند |
|---|---|
| هر تغییر، هرچند کوچک | `docs/state/active-context.md`, `docs/state/progress.md` |
| تصمیم معماری/فنی جدید | `docs/01-architecture.md` + یک ردیف در `docs/log/decisions.md` |
| قانون کسب‌وکار/محاسباتی جدید یا تغییر‌یافته | `docs/02-domain-rules.md` |
| تغییر هدف/دامنهٔ پروژه | `docs/00-brief.md` |
قبل از تحویل نهایی هر task:
- هم‌خوانی کد/رفتار واقعی با مستندات را چک کن.
- در خلاصهٔ پایانی، اسم فایل‌های مستنداتی که به‌روزرسانی شدند را ذکر کن.
- **هیچ فایلی حذف نشود** — فقط ویرایش/append.
## 6. خلاصهٔ پایان کار
بعد از هر task یک خلاصهٔ ۱ تا ۳ خطی بده: چه چیزی تغییر کرد، کدام فایل‌ها. توضیح طولانی نده مگر کاربر بخواهد.
## 7. جدول تصمیم سریع (Quick Reference)
| وضعیت | اقدام |
|---|---|
| دستور روشن و بدون تناقض | اجرا کن |
| دستور مبهم یا متناقض | توقف → `ambiguities.md` → سؤال |
| فایل موردنیاز پیدا نشد | توقف → از کاربر مسیر/محتوا را بپرس، حدس نزن |
| task بزرگ‌تر از یک feature | تقسیم به مراحل کوچک‌تر، تأیید ترتیب از کاربر |
| نیاز به تصمیم فنی جدید (کتابخانه، الگو، ساختار) | پیشنهاد بده + دلیل، منتظر تأیید، سپس در decisions.md ثبت کن |
+27
View File
@@ -0,0 +1,27 @@
# Project Init — راه‌اندازی یک پروژهٔ جدید از روی این تمپلیت
این فایل فقط یک‌بار در شروع پروژه اجرا می‌شود؛ بعد از تکمیل `docs/`، دیگر لازم نیست خوانده شود
(می‌توانی حذفش کنی یا در `archive/` نگه داری).
## مرحله ۱ — Discovery (این سؤالات را از کاربر بپرس، همه را با هم نه یکی‌یکی)
1. **پروژه چیست و چه مشکلی را حل می‌کند؟** (۲-۳ جمله)
2. **کاربر هدف کیست؟**
3. **Constraints سخت:** فرانت‌اند-فقط یا بک‌اند دارد؟ زبان/فریمورک اجباری؟ محدودیت هاستینگ/آفلاین بودن؟
4. **زبان و locale خروجی:** فارسی/انگلیسی؟ تقویم؟ واحد پول/عدد؟
5. **مدل داده:** منبع داده چیست (JSON محلی، دیتابیس، API خارجی)؟ چه موجودیت‌های اصلی‌ای دارد؟
6. **معیار تست:** بعد از هر تغییر چطور verify می‌شود؟ (باز کردن در مرورگر، `npm test`, اجرای اسکریپت، ...)
7. **چیزهایی که قطعاً نمی‌خواهیم** (Out of scope) — برای جلوگیری از scope creep.
## مرحله ۲ — پر کردن فایل‌ها
با پاسخ‌های بالا:
- `docs/00-brief.md` → سؤال ۱، ۲، ۷
- `docs/01-architecture.md` → سؤال ۳، ۵ (بخش تکنیکال)، ۶
- `docs/02-domain-rules.md` → سؤال ۴، ۵ (بخش قوانین کسب‌وکار) — اگر چیزی نامشخص است، خالی نگذار، در `docs/log/ambiguities.md` ثبت و سؤال کن
- `docs/state/active-context.md` و `docs/state/progress.md` → با «مرحله ۰: راه‌اندازی» شروع کن
## مرحله ۳ — تأیید
خلاصهٔ همهٔ فایل‌های پرشده را به کاربر نشان بده و قبل از شروع کدنویسی، تأیید صریح بگیر.
از این به بعد رفتار طبق `PLAYBOOK.md` است.
+57 -21
View File
@@ -1,36 +1,72 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
# آموزش آزاد دانشگاه صنعتی امیرکبیر
## Getting Started
سایت معرفی دوره‌ها و برنامه‌های آموزش آزاد — Next.js App Router، Atomic Design، SEO-ready، فارسی RTL، محتوا از PostgreSQL با پنل ادمین.
First, run the development server:
## پیش‌نیاز
- Node.js 20+
- PostgreSQL با `DATABASE_URL` برای اتصال.
## راه‌اندازی
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
npm install
cp .env.example .env.local # اگر موجود نیست؛ DATABASE_URL را بگذار
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
## پایگاه داده
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
```bash
node db/migrate.mjs # اعمال migration‌ها (نسبت به قبل)
node db/seed.mjs # seed محتوای mock به DB (قابل تکرار، upsert)
node scripts/seed-admin.mjs # کاربر ادمین اولیه → admin@aut.ac.ir / admin123
node scripts/test-db-connection.mjs # تست اتصال → CONNECTION_OK
```
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
> محیط تست: credential در `docs/03-database.md`.
## Learn More
## اجرا
To learn more about Next.js, take a look at the following resources:
```bash
npm run dev # http://localhost:3000
npm run build && npm start
```
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
- سایت عمومی: http://localhost:3000
- پنل ادمین: http://localhost:3000/admin (لاگین با کاربر seed شده)
- لندینگ حرفه‌ای: http://localhost:3000/professional
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## اسکریپت smoke (پس از `npm start`)
## Deploy on Vercel
```bash
SMOKE_ADMIN_EMAIL=admin@aut.ac.ir SMOKE_ADMIN_PASSWORD=admin123 node scripts/smoke.mjs
# خروجی SMOKE_OK
```
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
## API عمومی (قرارداد `{ data }`)
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
- `GET /api/courses` · `GET /api/courses/[id]`
- `GET /api/programs`
- `GET /api/events`
- `GET /api/articles`
- `POST /api/registrations` — ثبت علاقه (public)
## ساختار
- داده: `src/lib/data/*` (فقط DB) · مپرها: `src/lib/db/mappers.ts` · هویت استاتیک: `src/lib/site-config.ts`
- ادمین: registry در `src/lib/admin/entities.ts`؛ صفحات در `src/app/admin/(guard)/**`
- mock: فقط برای seed در `src/lib/mock/*` — runtime از آن import نمی‌کند
## مستندات ایجنت
شروع از `AGENTS.md` → `PLAYBOOK.md` → `docs/*`
- پلن و وضعیت: `docs/04-development-plan.md` · پیشرفت: `docs/state/progress.md`
- تصمیم‌ها: `docs/log/decisions.md` · دیتابیس: `docs/03-database.md`
## چک
```bash
npx tsc --noEmit
npm run lint
npm run build
```
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": true,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
+92
View File
@@ -0,0 +1,92 @@
// Phase A — migration runner
// Usage: node db/migrate.mjs
// Reads DATABASE_URL from .env.local if not already in the environment.
// Applies each file in db/migrations/*.sql in filename order, once, atomically.
// Tracks applied versions in a schema_migrations table; re-running is a no-op.
import { readFile, readdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { existsSync, readFileSync } from "node:fs";
import pg from "pg";
const { Client } = pg;
if (!process.env.DATABASE_URL) {
const envPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".env.local");
if (existsSync(envPath)) {
for (const line of readFileSync(envPath, "utf8").split(/\r?\n/)) {
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
if (match && !(match[1] in process.env)) {
process.env[match[1]] = match[2];
}
}
}
}
if (!process.env.DATABASE_URL) {
console.error("DATABASE_URL is not set and .env.local was not found.");
process.exit(1);
}
const migrationsDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "migrations");
async function main() {
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
try {
await client.query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ DEFAULT now()
)
`);
const appliedRes = await client.query("SELECT version FROM schema_migrations");
const applied = new Set(appliedRes.rows.map((r) => r.version));
const files = (await readdir(migrationsDir)).filter((f) => f.endsWith(".sql")).sort();
let appliedCount = 0;
const skipped = [];
for (const file of files) {
if (applied.has(file)) {
skipped.push(file);
continue;
}
const sql = await readFile(path.join(migrationsDir, file), "utf8");
try {
await client.query("BEGIN");
await client.query(sql);
await client.query("INSERT INTO schema_migrations (version) VALUES ($1)", [file]);
await client.query("COMMIT");
console.log("applied:", file);
appliedCount += 1;
} catch (error) {
await client.query("ROLLBACK").catch(() => {});
console.error("FAILED on:", file);
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
return;
}
}
const tables = await client.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name
`);
console.log(`applied_count: ${appliedCount}`);
console.log(`skipped (already applied): ${skipped.length ? skipped.join(", ") : "none"}`);
console.log(`tables_count: ${tables.rows.length}`);
console.log(JSON.stringify(tables.rows.map((r) => r.table_name)));
} finally {
await client.end().catch(() => {});
}
}
await main();
+215
View File
@@ -0,0 +1,215 @@
-- Phase A — Initial schema
-- Corresponds to docs/04-development-plan.md §3 (A.1–A.7) + site content tables.
-- All statements are idempotent (IF NOT EXISTS) so reruns are safe;
-- db/migrate.mjs additionally tracks applied versions in schema_migrations.
CREATE TABLE IF NOT EXISTS courses (
id TEXT PRIMARY KEY,
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
summary TEXT NOT NULL,
category TEXT NOT NULL
CHECK (category IN ('leadership','technology','innovation','energy','design','digital')),
duration_hours INT NOT NULL CHECK (duration_hours > 0),
format TEXT NOT NULL
CHECK (format IN ('online','blended','in-person')),
registration_url TEXT NOT NULL,
image_url TEXT NOT NULL,
seo_description TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now(),
published BOOLEAN DEFAULT true
);
CREATE TABLE IF NOT EXISTS programs (
id TEXT PRIMARY KEY,
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
blurb TEXT NOT NULL,
group_key TEXT NOT NULL
CHECK (group_key IN ('standard','executive')),
href TEXT NOT NULL,
tagline TEXT NULL,
audience TEXT NOT NULL,
duration_label TEXT NOT NULL,
format_label TEXT NOT NULL,
highlights JSONB NOT NULL DEFAULT '[]',
body TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
start_date DATE NOT NULL,
end_date DATE NULL,
location TEXT NOT NULL,
href TEXT NOT NULL,
summary TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS articles (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
category TEXT NOT NULL,
excerpt TEXT NOT NULL,
image_url TEXT NOT NULL,
href TEXT NOT NULL,
featured BOOLEAN NOT NULL DEFAULT false,
body TEXT NOT NULL,
published_at DATE NOT NULL,
author TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- Domain rule: at most one *published* featured article (docs/02-domain-rules.md §Business + plan §A.4).
CREATE UNIQUE INDEX IF NOT EXISTS articles_one_featured
ON articles ((featured))
WHERE featured = true AND published = true;
-- Site content (plan §A.5) — matches src/lib/types/* entities.
CREATE TABLE IF NOT EXISTS intersection_topics (
id TEXT PRIMARY KEY,
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
href TEXT NOT NULL,
image_url TEXT NOT NULL,
body TEXT NOT NULL,
highlights JSONB NOT NULL DEFAULT '[]',
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS faculty_members (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
title TEXT NOT NULL,
focus TEXT NOT NULL,
bio TEXT NOT NULL,
image_url TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS alumni_stories (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
excerpt TEXT NOT NULL,
name TEXT NOT NULL,
program TEXT NOT NULL,
image_url TEXT NOT NULL,
href TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS campaign_banners (
id TEXT PRIMARY KEY,
version TEXT NOT NULL,
text TEXT NOT NULL,
href TEXT NOT NULL,
cta TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS legal_pages (
slug TEXT PRIMARY KEY,
title TEXT NOT NULL,
body JSONB NOT NULL DEFAULT '[]',
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS site_stats (
id TEXT PRIMARY KEY,
value TEXT NOT NULL,
label TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS testimonials (
id TEXT PRIMARY KEY,
quote TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT NOT NULL,
course_title TEXT NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- Registration leads (plan §A.6, used in phase G).
CREATE TABLE IF NOT EXISTS registration_leads (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
course_id TEXT NULL REFERENCES courses(id) ON DELETE SET NULL,
course_slug TEXT NULL,
full_name TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT NULL,
message TEXT NULL,
source TEXT NOT NULL DEFAULT 'register_page',
status TEXT NOT NULL DEFAULT 'new'
CHECK (status IN ('new','contacted','enrolled','rejected')),
created_at TIMESTAMPTZ DEFAULT now()
);
-- Admin (plan §A.7, used in phase E).
CREATE TABLE IF NOT EXISTS admin_users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'admin',
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS admin_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
token_hash TEXT UNIQUE NOT NULL,
user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- Keep updated_at meaningful on every write (used by admin CRUD in later phases).
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DO $$
DECLARE
t TEXT;
BEGIN
FOREACH t IN ARRAY ARRAY[
'courses','programs','events','articles',
'intersection_topics','faculty_members','alumni_stories',
'campaign_banners','legal_pages','site_stats','testimonials'
]
LOOP
EXECUTE format(
'CREATE TRIGGER trg_%I_set_updated_at BEFORE UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION set_updated_at()',
t, t
);
END LOOP;
END;
$$;
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff. Show more