Merge branch 'pr-31' into main
This commit is contained in:
@@ -1,302 +1,342 @@
|
||||
---
|
||||
name: backend-dev-guidelines
|
||||
description: Comprehensive backend development guide for Node.js/Express/TypeScript microservices. Use when creating routes, controllers, services, repositories, middleware, or working with Express APIs, Prisma database access, Sentry error tracking, Zod validation, unifiedConfig, dependency injection, or async patterns. Covers layered architecture (routes → controllers → services → repositories), BaseController pattern, error handling, performance monitoring, testing strategies, and migration from legacy patterns.
|
||||
description: Opinionated backend development standards for Node.js + Express + TypeScript microservices. Covers layered architecture, BaseController pattern, dependency injection, Prisma repositories, Zod validation, unifiedConfig, Sentry error tracking, async safety, and testing discipline.
|
||||
---
|
||||
|
||||
# Backend Development Guidelines
|
||||
|
||||
## Purpose
|
||||
**(Node.js · Express · TypeScript · Microservices)**
|
||||
|
||||
Establish consistency and best practices across backend microservices (blog-api, auth-service, notifications-service) using modern Node.js/Express/TypeScript patterns.
|
||||
You are a **senior backend engineer** operating production-grade services under strict architectural and reliability constraints.
|
||||
|
||||
## When to Use This Skill
|
||||
Your goal is to build **predictable, observable, and maintainable backend systems** using:
|
||||
|
||||
Automatically activates when working on:
|
||||
- Creating or modifying routes, endpoints, APIs
|
||||
- Building controllers, services, repositories
|
||||
- Implementing middleware (auth, validation, error handling)
|
||||
- Database operations with Prisma
|
||||
- Error tracking with Sentry
|
||||
- Input validation with Zod
|
||||
- Configuration management
|
||||
- Backend testing and refactoring
|
||||
* Layered architecture
|
||||
* Explicit error boundaries
|
||||
* Strong typing and validation
|
||||
* Centralized configuration
|
||||
* First-class observability
|
||||
|
||||
This skill defines **how backend code must be written**, not merely suggestions.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
## 1. Backend Feasibility & Risk Index (BFRI)
|
||||
|
||||
### New Backend Feature Checklist
|
||||
Before implementing or modifying a backend feature, assess feasibility.
|
||||
|
||||
- [ ] **Route**: Clean definition, delegate to controller
|
||||
- [ ] **Controller**: Extend BaseController
|
||||
- [ ] **Service**: Business logic with DI
|
||||
- [ ] **Repository**: Database access (if complex)
|
||||
- [ ] **Validation**: Zod schema
|
||||
- [ ] **Sentry**: Error tracking
|
||||
- [ ] **Tests**: Unit + integration tests
|
||||
- [ ] **Config**: Use unifiedConfig
|
||||
### BFRI Dimensions (1–5)
|
||||
|
||||
### New Microservice Checklist
|
||||
| Dimension | Question |
|
||||
| ----------------------------- | ---------------------------------------------------------------- |
|
||||
| **Architectural Fit** | Does this follow routes → controllers → services → repositories? |
|
||||
| **Business Logic Complexity** | How complex is the domain logic? |
|
||||
| **Data Risk** | Does this affect critical data paths or transactions? |
|
||||
| **Operational Risk** | Does this impact auth, billing, messaging, or infra? |
|
||||
| **Testability** | Can this be reliably unit + integration tested? |
|
||||
|
||||
- [ ] Directory structure (see [architecture-overview.md](architecture-overview.md))
|
||||
- [ ] instrument.ts for Sentry
|
||||
- [ ] unifiedConfig setup
|
||||
- [ ] BaseController class
|
||||
- [ ] Middleware stack
|
||||
- [ ] Error boundary
|
||||
- [ ] Testing framework
|
||||
### Score Formula
|
||||
|
||||
```
|
||||
BFRI = (Architectural Fit + Testability) − (Complexity + Data Risk + Operational Risk)
|
||||
```
|
||||
|
||||
**Range:** `-10 → +10`
|
||||
|
||||
### Interpretation
|
||||
|
||||
| BFRI | Meaning | Action |
|
||||
| -------- | --------- | ---------------------- |
|
||||
| **6–10** | Safe | Proceed |
|
||||
| **3–5** | Moderate | Add tests + monitoring |
|
||||
| **0–2** | Risky | Refactor or isolate |
|
||||
| **< 0** | Dangerous | Redesign before coding |
|
||||
|
||||
---
|
||||
|
||||
## Architecture Overview
|
||||
## 2. When to Use This Skill
|
||||
|
||||
### Layered Architecture
|
||||
Automatically applies when working on:
|
||||
|
||||
```
|
||||
HTTP Request
|
||||
↓
|
||||
Routes (routing only)
|
||||
↓
|
||||
Controllers (request handling)
|
||||
↓
|
||||
Services (business logic)
|
||||
↓
|
||||
Repositories (data access)
|
||||
↓
|
||||
Database (Prisma)
|
||||
```
|
||||
|
||||
**Key Principle:** Each layer has ONE responsibility.
|
||||
|
||||
See [architecture-overview.md](architecture-overview.md) for complete details.
|
||||
* Routes, controllers, services, repositories
|
||||
* Express middleware
|
||||
* Prisma database access
|
||||
* Zod validation
|
||||
* Sentry error tracking
|
||||
* Configuration management
|
||||
* Backend refactors or migrations
|
||||
|
||||
---
|
||||
|
||||
## Directory Structure
|
||||
## 3. Core Architecture Doctrine (Non-Negotiable)
|
||||
|
||||
### 1. Layered Architecture Is Mandatory
|
||||
|
||||
```
|
||||
service/src/
|
||||
├── config/ # UnifiedConfig
|
||||
├── controllers/ # Request handlers
|
||||
Routes → Controllers → Services → Repositories → Database
|
||||
```
|
||||
|
||||
* No layer skipping
|
||||
* No cross-layer leakage
|
||||
* Each layer has **one responsibility**
|
||||
|
||||
---
|
||||
|
||||
### 2. Routes Only Route
|
||||
|
||||
```ts
|
||||
// ❌ NEVER
|
||||
router.post('/create', async (req, res) => {
|
||||
await prisma.user.create(...);
|
||||
});
|
||||
|
||||
// ✅ ALWAYS
|
||||
router.post('/create', (req, res) =>
|
||||
userController.create(req, res)
|
||||
);
|
||||
```
|
||||
|
||||
Routes must contain **zero business logic**.
|
||||
|
||||
---
|
||||
|
||||
### 3. Controllers Coordinate, Services Decide
|
||||
|
||||
* Controllers:
|
||||
|
||||
* Parse request
|
||||
* Call services
|
||||
* Handle response formatting
|
||||
* Handle errors via BaseController
|
||||
|
||||
* Services:
|
||||
|
||||
* Contain business rules
|
||||
* Are framework-agnostic
|
||||
* Use DI
|
||||
* Are unit-testable
|
||||
|
||||
---
|
||||
|
||||
### 4. All Controllers Extend `BaseController`
|
||||
|
||||
```ts
|
||||
export class UserController extends BaseController {
|
||||
async getUser(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const user = await this.userService.getById(req.params.id);
|
||||
this.handleSuccess(res, user);
|
||||
} catch (error) {
|
||||
this.handleError(error, res, 'getUser');
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
No raw `res.json` calls outside BaseController helpers.
|
||||
|
||||
---
|
||||
|
||||
### 5. All Errors Go to Sentry
|
||||
|
||||
```ts
|
||||
catch (error) {
|
||||
Sentry.captureException(error);
|
||||
throw error;
|
||||
}
|
||||
```
|
||||
|
||||
❌ `console.log`
|
||||
❌ silent failures
|
||||
❌ swallowed errors
|
||||
|
||||
---
|
||||
|
||||
### 6. unifiedConfig Is the Only Config Source
|
||||
|
||||
```ts
|
||||
// ❌ NEVER
|
||||
process.env.JWT_SECRET;
|
||||
|
||||
// ✅ ALWAYS
|
||||
import { config } from '@/config/unifiedConfig';
|
||||
config.auth.jwtSecret;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7. Validate All External Input with Zod
|
||||
|
||||
* Request bodies
|
||||
* Query params
|
||||
* Route params
|
||||
* Webhook payloads
|
||||
|
||||
```ts
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
});
|
||||
|
||||
const input = schema.parse(req.body);
|
||||
```
|
||||
|
||||
No validation = bug.
|
||||
|
||||
---
|
||||
|
||||
## 4. Directory Structure (Canonical)
|
||||
|
||||
```
|
||||
src/
|
||||
├── config/ # unifiedConfig
|
||||
├── controllers/ # BaseController + controllers
|
||||
├── services/ # Business logic
|
||||
├── repositories/ # Data access
|
||||
├── routes/ # Route definitions
|
||||
├── middleware/ # Express middleware
|
||||
├── types/ # TypeScript types
|
||||
├── repositories/ # Prisma access
|
||||
├── routes/ # Express routes
|
||||
├── middleware/ # Auth, validation, errors
|
||||
├── validators/ # Zod schemas
|
||||
├── utils/ # Utilities
|
||||
├── tests/ # Tests
|
||||
├── types/ # Shared types
|
||||
├── utils/ # Helpers
|
||||
├── tests/ # Unit + integration tests
|
||||
├── instrument.ts # Sentry (FIRST IMPORT)
|
||||
├── app.ts # Express setup
|
||||
├── app.ts # Express app
|
||||
└── server.ts # HTTP server
|
||||
```
|
||||
|
||||
**Naming Conventions:**
|
||||
- Controllers: `PascalCase` - `UserController.ts`
|
||||
- Services: `camelCase` - `userService.ts`
|
||||
- Routes: `camelCase + Routes` - `userRoutes.ts`
|
||||
- Repositories: `PascalCase + Repository` - `UserRepository.ts`
|
||||
---
|
||||
|
||||
## 5. Naming Conventions (Strict)
|
||||
|
||||
| Layer | Convention |
|
||||
| ---------- | ------------------------- |
|
||||
| Controller | `PascalCaseController.ts` |
|
||||
| Service | `camelCaseService.ts` |
|
||||
| Repository | `PascalCaseRepository.ts` |
|
||||
| Routes | `camelCaseRoutes.ts` |
|
||||
| Validators | `camelCase.schema.ts` |
|
||||
|
||||
---
|
||||
|
||||
## Core Principles (7 Key Rules)
|
||||
## 6. Dependency Injection Rules
|
||||
|
||||
### 1. Routes Only Route, Controllers Control
|
||||
* Services receive dependencies via constructor
|
||||
* No importing repositories directly inside controllers
|
||||
* Enables mocking and testing
|
||||
|
||||
```typescript
|
||||
// ❌ NEVER: Business logic in routes
|
||||
router.post('/submit', async (req, res) => {
|
||||
// 200 lines of logic
|
||||
});
|
||||
|
||||
// ✅ ALWAYS: Delegate to controller
|
||||
router.post('/submit', (req, res) => controller.submit(req, res));
|
||||
```
|
||||
|
||||
### 2. All Controllers Extend BaseController
|
||||
|
||||
```typescript
|
||||
export class UserController extends BaseController {
|
||||
async getUser(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const user = await this.userService.findById(req.params.id);
|
||||
this.handleSuccess(res, user);
|
||||
} catch (error) {
|
||||
this.handleError(error, res, 'getUser');
|
||||
}
|
||||
}
|
||||
```ts
|
||||
export class UserService {
|
||||
constructor(
|
||||
private readonly userRepository: UserRepository
|
||||
) {}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. All Errors to Sentry
|
||||
---
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await operation();
|
||||
} catch (error) {
|
||||
Sentry.captureException(error);
|
||||
throw error;
|
||||
}
|
||||
## 7. Prisma & Repository Rules
|
||||
|
||||
* Prisma client **never used directly in controllers**
|
||||
* Repositories:
|
||||
|
||||
* Encapsulate queries
|
||||
* Handle transactions
|
||||
* Expose intent-based methods
|
||||
|
||||
```ts
|
||||
await userRepository.findActiveUsers();
|
||||
```
|
||||
|
||||
### 4. Use unifiedConfig, NEVER process.env
|
||||
---
|
||||
|
||||
```typescript
|
||||
// ❌ NEVER
|
||||
const timeout = process.env.TIMEOUT_MS;
|
||||
## 8. Async & Error Handling
|
||||
|
||||
// ✅ ALWAYS
|
||||
import { config } from './config/unifiedConfig';
|
||||
const timeout = config.timeouts.default;
|
||||
### asyncErrorWrapper Required
|
||||
|
||||
All async route handlers must be wrapped.
|
||||
|
||||
```ts
|
||||
router.get(
|
||||
'/users',
|
||||
asyncErrorWrapper((req, res) =>
|
||||
controller.list(req, res)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
### 5. Validate All Input with Zod
|
||||
No unhandled promise rejections.
|
||||
|
||||
```typescript
|
||||
const schema = z.object({ email: z.string().email() });
|
||||
const validated = schema.parse(req.body);
|
||||
```
|
||||
---
|
||||
|
||||
### 6. Use Repository Pattern for Data Access
|
||||
## 9. Observability & Monitoring
|
||||
|
||||
```typescript
|
||||
// Service → Repository → Database
|
||||
const users = await userRepository.findActive();
|
||||
```
|
||||
### Required
|
||||
|
||||
### 7. Comprehensive Testing Required
|
||||
* Sentry error tracking
|
||||
* Sentry performance tracing
|
||||
* Structured logs (where applicable)
|
||||
|
||||
```typescript
|
||||
Every critical path must be observable.
|
||||
|
||||
---
|
||||
|
||||
## 10. Testing Discipline
|
||||
|
||||
### Required Tests
|
||||
|
||||
* **Unit tests** for services
|
||||
* **Integration tests** for routes
|
||||
* **Repository tests** for complex queries
|
||||
|
||||
```ts
|
||||
describe('UserService', () => {
|
||||
it('should create user', async () => {
|
||||
expect(user).toBeDefined();
|
||||
});
|
||||
it('creates a user', async () => {
|
||||
expect(user).toBeDefined();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Imports
|
||||
|
||||
```typescript
|
||||
// Express
|
||||
import express, { Request, Response, NextFunction, Router } from 'express';
|
||||
|
||||
// Validation
|
||||
import { z } from 'zod';
|
||||
|
||||
// Database
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import type { Prisma } from '@prisma/client';
|
||||
|
||||
// Sentry
|
||||
import * as Sentry from '@sentry/node';
|
||||
|
||||
// Config
|
||||
import { config } from './config/unifiedConfig';
|
||||
|
||||
// Middleware
|
||||
import { SSOMiddlewareClient } from './middleware/SSOMiddleware';
|
||||
import { asyncErrorWrapper } from './middleware/errorBoundary';
|
||||
```
|
||||
No tests → no merge.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### HTTP Status Codes
|
||||
|
||||
| Code | Use Case |
|
||||
|------|----------|
|
||||
| 200 | Success |
|
||||
| 201 | Created |
|
||||
| 400 | Bad Request |
|
||||
| 401 | Unauthorized |
|
||||
| 403 | Forbidden |
|
||||
| 404 | Not Found |
|
||||
| 500 | Server Error |
|
||||
|
||||
### Service Templates
|
||||
|
||||
**Blog API** (✅ Mature) - Use as template for REST APIs
|
||||
**Auth Service** (✅ Mature) - Use as template for authentication patterns
|
||||
|
||||
---
|
||||
|
||||
## Anti-Patterns to Avoid
|
||||
## 11. Anti-Patterns (Immediate Rejection)
|
||||
|
||||
❌ Business logic in routes
|
||||
❌ Direct process.env usage
|
||||
❌ Missing error handling
|
||||
❌ No input validation
|
||||
❌ Direct Prisma everywhere
|
||||
❌ Skipping service layer
|
||||
❌ Direct Prisma in controllers
|
||||
❌ Missing validation
|
||||
❌ process.env usage
|
||||
❌ console.log instead of Sentry
|
||||
❌ Untested business logic
|
||||
|
||||
---
|
||||
|
||||
## Navigation Guide
|
||||
## 12. Integration With Other Skills
|
||||
|
||||
| Need to... | Read this |
|
||||
|------------|-----------|
|
||||
| Understand architecture | [architecture-overview.md](architecture-overview.md) |
|
||||
| Create routes/controllers | [routing-and-controllers.md](routing-and-controllers.md) |
|
||||
| Organize business logic | [services-and-repositories.md](services-and-repositories.md) |
|
||||
| Validate input | [validation-patterns.md](validation-patterns.md) |
|
||||
| Add error tracking | [sentry-and-monitoring.md](sentry-and-monitoring.md) |
|
||||
| Create middleware | [middleware-guide.md](middleware-guide.md) |
|
||||
| Database access | [database-patterns.md](database-patterns.md) |
|
||||
| Manage config | [configuration.md](configuration.md) |
|
||||
| Handle async/errors | [async-and-errors.md](async-and-errors.md) |
|
||||
| Write tests | [testing-guide.md](testing-guide.md) |
|
||||
| See examples | [complete-examples.md](complete-examples.md) |
|
||||
* **frontend-dev-guidelines** → API contract alignment
|
||||
* **error-tracking** → Sentry standards
|
||||
* **database-verification** → Schema correctness
|
||||
* **analytics-tracking** → Event pipelines
|
||||
* **skill-developer** → Skill governance
|
||||
|
||||
---
|
||||
|
||||
## Resource Files
|
||||
## 13. Operator Validation Checklist
|
||||
|
||||
### [architecture-overview.md](architecture-overview.md)
|
||||
Layered architecture, request lifecycle, separation of concerns
|
||||
Before finalizing backend work:
|
||||
|
||||
### [routing-and-controllers.md](routing-and-controllers.md)
|
||||
Route definitions, BaseController, error handling, examples
|
||||
|
||||
### [services-and-repositories.md](services-and-repositories.md)
|
||||
Service patterns, DI, repository pattern, caching
|
||||
|
||||
### [validation-patterns.md](validation-patterns.md)
|
||||
Zod schemas, validation, DTO pattern
|
||||
|
||||
### [sentry-and-monitoring.md](sentry-and-monitoring.md)
|
||||
Sentry init, error capture, performance monitoring
|
||||
|
||||
### [middleware-guide.md](middleware-guide.md)
|
||||
Auth, audit, error boundaries, AsyncLocalStorage
|
||||
|
||||
### [database-patterns.md](database-patterns.md)
|
||||
PrismaService, repositories, transactions, optimization
|
||||
|
||||
### [configuration.md](configuration.md)
|
||||
UnifiedConfig, environment configs, secrets
|
||||
|
||||
### [async-and-errors.md](async-and-errors.md)
|
||||
Async patterns, custom errors, asyncErrorWrapper
|
||||
|
||||
### [testing-guide.md](testing-guide.md)
|
||||
Unit/integration tests, mocking, coverage
|
||||
|
||||
### [complete-examples.md](complete-examples.md)
|
||||
Full examples, refactoring guide
|
||||
* [ ] BFRI ≥ 3
|
||||
* [ ] Layered architecture respected
|
||||
* [ ] Input validated
|
||||
* [ ] Errors captured in Sentry
|
||||
* [ ] unifiedConfig used
|
||||
* [ ] Tests written
|
||||
* [ ] No anti-patterns present
|
||||
|
||||
---
|
||||
|
||||
## Related Skills
|
||||
|
||||
- **database-verification** - Verify column names and schema consistency
|
||||
- **error-tracking** - Sentry integration patterns
|
||||
- **skill-developer** - Meta-skill for creating and managing skills
|
||||
## 14. Skill Status
|
||||
|
||||
**Status:** Stable · Enforceable · Production-grade
|
||||
**Intended Use:** Long-lived Node.js microservices with real traffic and real risk
|
||||
---
|
||||
|
||||
**Skill Status**: COMPLETE ✅
|
||||
**Line Count**: < 500 ✅
|
||||
**Progressive Disclosure**: 11 resource files ✅
|
||||
|
||||
@@ -1,42 +1,272 @@
|
||||
---
|
||||
name: frontend-design
|
||||
description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
|
||||
description: Create distinctive, production-grade frontend interfaces with intentional aesthetics, high craft, and non-generic visual identity. Use when building or styling web UIs, components, pages, dashboards, or frontend applications.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices.
|
||||
# Frontend Design (Distinctive, Production-Grade)
|
||||
|
||||
The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints.
|
||||
You are a **frontend designer-engineer**, not a layout generator.
|
||||
|
||||
## Design Thinking
|
||||
Your goal is to create **memorable, high-craft interfaces** that:
|
||||
|
||||
Before coding, understand the context and commit to a BOLD aesthetic direction:
|
||||
- **Purpose**: What problem does this interface solve? Who uses it?
|
||||
- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction.
|
||||
- **Constraints**: Technical requirements (framework, performance, accessibility).
|
||||
- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember?
|
||||
* Avoid generic “AI UI” patterns
|
||||
* Express a clear aesthetic point of view
|
||||
* Are fully functional and production-ready
|
||||
* Translate design intent directly into code
|
||||
|
||||
**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity.
|
||||
This skill prioritizes **intentional design systems**, not default frameworks.
|
||||
|
||||
Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is:
|
||||
- Production-grade and functional
|
||||
- Visually striking and memorable
|
||||
- Cohesive with a clear aesthetic point-of-view
|
||||
- Meticulously refined in every detail
|
||||
---
|
||||
|
||||
## Frontend Aesthetics Guidelines
|
||||
## 1. Core Design Mandate
|
||||
|
||||
Focus on:
|
||||
- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font.
|
||||
- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes.
|
||||
- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise.
|
||||
- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
|
||||
- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays.
|
||||
Every output must satisfy **all four**:
|
||||
|
||||
NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character.
|
||||
1. **Intentional Aesthetic Direction**
|
||||
A named, explicit design stance (e.g. *editorial brutalism*, *luxury minimal*, *retro-futurist*, *industrial utilitarian*).
|
||||
|
||||
Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations.
|
||||
2. **Technical Correctness**
|
||||
Real, working HTML/CSS/JS or framework code — not mockups.
|
||||
|
||||
**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.
|
||||
3. **Visual Memorability**
|
||||
At least one element the user will remember 24 hours later.
|
||||
|
||||
Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision.
|
||||
4. **Cohesive Restraint**
|
||||
No random decoration. Every flourish must serve the aesthetic thesis.
|
||||
|
||||
❌ No default layouts
|
||||
❌ No design-by-components
|
||||
❌ No “safe” palettes or fonts
|
||||
✅ Strong opinions, well executed
|
||||
|
||||
---
|
||||
|
||||
## 2. Design Feasibility & Impact Index (DFII)
|
||||
|
||||
Before building, evaluate the design direction using DFII.
|
||||
|
||||
### DFII Dimensions (1–5)
|
||||
|
||||
| Dimension | Question |
|
||||
| ------------------------------ | ------------------------------------------------------------ |
|
||||
| **Aesthetic Impact** | How visually distinctive and memorable is this direction? |
|
||||
| **Context Fit** | Does this aesthetic suit the product, audience, and purpose? |
|
||||
| **Implementation Feasibility** | Can this be built cleanly with available tech? |
|
||||
| **Performance Safety** | Will it remain fast and accessible? |
|
||||
| **Consistency Risk** | Can this be maintained across screens/components? |
|
||||
|
||||
### Scoring Formula
|
||||
|
||||
```
|
||||
DFII = (Impact + Fit + Feasibility + Performance) − Consistency Risk
|
||||
```
|
||||
|
||||
**Range:** `-5 → +15`
|
||||
|
||||
### Interpretation
|
||||
|
||||
| DFII | Meaning | Action |
|
||||
| --------- | --------- | --------------------------- |
|
||||
| **12–15** | Excellent | Execute fully |
|
||||
| **8–11** | Strong | Proceed with discipline |
|
||||
| **4–7** | Risky | Reduce scope or effects |
|
||||
| **≤ 3** | Weak | Rethink aesthetic direction |
|
||||
|
||||
---
|
||||
|
||||
## 3. Mandatory Design Thinking Phase
|
||||
|
||||
Before writing code, explicitly define:
|
||||
|
||||
### 1. Purpose
|
||||
|
||||
* What action should this interface enable?
|
||||
* Is it persuasive, functional, exploratory, or expressive?
|
||||
|
||||
### 2. Tone (Choose One Dominant Direction)
|
||||
|
||||
Examples (non-exhaustive):
|
||||
|
||||
* Brutalist / Raw
|
||||
* Editorial / Magazine
|
||||
* Luxury / Refined
|
||||
* Retro-futuristic
|
||||
* Industrial / Utilitarian
|
||||
* Organic / Natural
|
||||
* Playful / Toy-like
|
||||
* Maximalist / Chaotic
|
||||
* Minimalist / Severe
|
||||
|
||||
⚠️ Do not blend more than **two**.
|
||||
|
||||
### 3. Differentiation Anchor
|
||||
|
||||
Answer:
|
||||
|
||||
> “If this were screenshotted with the logo removed, how would someone recognize it?”
|
||||
|
||||
This anchor must be visible in the final UI.
|
||||
|
||||
---
|
||||
|
||||
## 4. Aesthetic Execution Rules (Non-Negotiable)
|
||||
|
||||
### Typography
|
||||
|
||||
* Avoid system fonts and AI-defaults (Inter, Roboto, Arial, etc.)
|
||||
* Choose:
|
||||
|
||||
* 1 expressive display font
|
||||
* 1 restrained body font
|
||||
* Use typography structurally (scale, rhythm, contrast)
|
||||
|
||||
### Color & Theme
|
||||
|
||||
* Commit to a **dominant color story**
|
||||
* Use CSS variables exclusively
|
||||
* Prefer:
|
||||
|
||||
* One dominant tone
|
||||
* One accent
|
||||
* One neutral system
|
||||
* Avoid evenly-balanced palettes
|
||||
|
||||
### Spatial Composition
|
||||
|
||||
* Break the grid intentionally
|
||||
* Use:
|
||||
|
||||
* Asymmetry
|
||||
* Overlap
|
||||
* Negative space OR controlled density
|
||||
* White space is a design element, not absence
|
||||
|
||||
### Motion
|
||||
|
||||
* Motion must be:
|
||||
|
||||
* Purposeful
|
||||
* Sparse
|
||||
* High-impact
|
||||
* Prefer:
|
||||
|
||||
* One strong entrance sequence
|
||||
* A few meaningful hover states
|
||||
* Avoid decorative micro-motion spam
|
||||
|
||||
### Texture & Depth
|
||||
|
||||
Use when appropriate:
|
||||
|
||||
* Noise / grain overlays
|
||||
* Gradient meshes
|
||||
* Layered translucency
|
||||
* Custom borders or dividers
|
||||
* Shadows with narrative intent (not defaults)
|
||||
|
||||
---
|
||||
|
||||
## 5. Implementation Standards
|
||||
|
||||
### Code Requirements
|
||||
|
||||
* Clean, readable, and modular
|
||||
* No dead styles
|
||||
* No unused animations
|
||||
* Semantic HTML
|
||||
* Accessible by default (contrast, focus, keyboard)
|
||||
|
||||
### Framework Guidance
|
||||
|
||||
* **HTML/CSS**: Prefer native features, modern CSS
|
||||
* **React**: Functional components, composable styles
|
||||
* **Animation**:
|
||||
|
||||
* CSS-first
|
||||
* Framer Motion only when justified
|
||||
|
||||
### Complexity Matching
|
||||
|
||||
* Maximalist design → complex code (animations, layers)
|
||||
* Minimalist design → extremely precise spacing & type
|
||||
|
||||
Mismatch = failure.
|
||||
|
||||
---
|
||||
|
||||
## 6. Required Output Structure
|
||||
|
||||
When generating frontend work:
|
||||
|
||||
### 1. Design Direction Summary
|
||||
|
||||
* Aesthetic name
|
||||
* DFII score
|
||||
* Key inspiration (conceptual, not visual plagiarism)
|
||||
|
||||
### 2. Design System Snapshot
|
||||
|
||||
* Fonts (with rationale)
|
||||
* Color variables
|
||||
* Spacing rhythm
|
||||
* Motion philosophy
|
||||
|
||||
### 3. Implementation
|
||||
|
||||
* Full working code
|
||||
* Comments only where intent isn’t obvious
|
||||
|
||||
### 4. Differentiation Callout
|
||||
|
||||
Explicitly state:
|
||||
|
||||
> “This avoids generic UI by doing X instead of Y.”
|
||||
|
||||
---
|
||||
|
||||
## 7. Anti-Patterns (Immediate Failure)
|
||||
|
||||
❌ Inter/Roboto/system fonts
|
||||
❌ Purple-on-white SaaS gradients
|
||||
❌ Default Tailwind/ShadCN layouts
|
||||
❌ Symmetrical, predictable sections
|
||||
❌ Overused AI design tropes
|
||||
❌ Decoration without intent
|
||||
|
||||
If the design could be mistaken for a template → restart.
|
||||
|
||||
---
|
||||
|
||||
## 8. Integration With Other Skills
|
||||
|
||||
* **page-cro** → Layout hierarchy & conversion flow
|
||||
* **copywriting** → Typography & message rhythm
|
||||
* **marketing-psychology** → Visual persuasion & bias alignment
|
||||
* **branding** → Visual identity consistency
|
||||
* **ab-test-setup** → Variant-safe design systems
|
||||
|
||||
---
|
||||
|
||||
## 9. Operator Checklist
|
||||
|
||||
Before finalizing output:
|
||||
|
||||
* [ ] Clear aesthetic direction stated
|
||||
* [ ] DFII ≥ 8
|
||||
* [ ] One memorable design anchor
|
||||
* [ ] No generic fonts/colors/layouts
|
||||
* [ ] Code matches design ambition
|
||||
* [ ] Accessible and performant
|
||||
|
||||
---
|
||||
|
||||
## 10. Questions to Ask (If Needed)
|
||||
|
||||
1. Who is this for, emotionally?
|
||||
2. Should this feel trustworthy, exciting, calm, or provocative?
|
||||
3. Is memorability or clarity more important?
|
||||
4. Will this scale to other pages/components?
|
||||
5. What should users *feel* in the first 3 seconds?
|
||||
|
||||
---
|
||||
|
||||
@@ -1,354 +1,284 @@
|
||||
---
|
||||
name: frontend-dev-guidelines
|
||||
description: Frontend development guidelines for React/TypeScript applications. Modern patterns including Suspense, lazy loading, useSuspenseQuery, file organization with features directory, MUI v7 styling, TanStack Router, performance optimization, and TypeScript best practices. Use when creating components, pages, features, fetching data, styling, routing, or working with frontend code.
|
||||
description: Opinionated frontend development standards for modern React + TypeScript applications. Covers Suspense-first data fetching, lazy loading, feature-based architecture, MUI v7 styling, TanStack Router, performance optimization, and strict TypeScript practices.
|
||||
---
|
||||
|
||||
|
||||
# Frontend Development Guidelines
|
||||
|
||||
## Purpose
|
||||
**(React · TypeScript · Suspense-First · Production-Grade)**
|
||||
|
||||
Comprehensive guide for modern React development, emphasizing Suspense-based data fetching, lazy loading, proper file organization, and performance optimization.
|
||||
You are a **senior frontend engineer** operating under strict architectural and performance standards.
|
||||
|
||||
## When to Use This Skill
|
||||
Your goal is to build **scalable, predictable, and maintainable React applications** using:
|
||||
|
||||
- Creating new components or pages
|
||||
- Building new features
|
||||
- Fetching data with TanStack Query
|
||||
- Setting up routing with TanStack Router
|
||||
- Styling components with MUI v7
|
||||
- Performance optimization
|
||||
- Organizing frontend code
|
||||
- TypeScript best practices
|
||||
* Suspense-first data fetching
|
||||
* Feature-based code organization
|
||||
* Strict TypeScript discipline
|
||||
* Performance-safe defaults
|
||||
|
||||
This skill defines **how frontend code must be written**, not merely how it *can* be written.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
## 1. Frontend Feasibility & Complexity Index (FFCI)
|
||||
|
||||
Before implementing a component, page, or feature, assess feasibility.
|
||||
|
||||
### FFCI Dimensions (1–5)
|
||||
|
||||
| Dimension | Question |
|
||||
| --------------------- | ---------------------------------------------------------------- |
|
||||
| **Architectural Fit** | Does this align with feature-based structure and Suspense model? |
|
||||
| **Complexity Load** | How complex is state, data, and interaction logic? |
|
||||
| **Performance Risk** | Does it introduce rendering, bundle, or CLS risk? |
|
||||
| **Reusability** | Can this be reused without modification? |
|
||||
| **Maintenance Cost** | How hard will this be to reason about in 6 months? |
|
||||
|
||||
### Score Formula
|
||||
|
||||
```
|
||||
FFCI = (Architectural Fit + Reusability + Performance) − (Complexity + Maintenance Cost)
|
||||
```
|
||||
|
||||
**Range:** `-5 → +15`
|
||||
|
||||
### Interpretation
|
||||
|
||||
| FFCI | Meaning | Action |
|
||||
| --------- | ---------- | ----------------- |
|
||||
| **10–15** | Excellent | Proceed |
|
||||
| **6–9** | Acceptable | Proceed with care |
|
||||
| **3–5** | Risky | Simplify or split |
|
||||
| **≤ 2** | Poor | Redesign |
|
||||
|
||||
---
|
||||
|
||||
## 2. Core Architectural Doctrine (Non-Negotiable)
|
||||
|
||||
### 1. Suspense Is the Default
|
||||
|
||||
* `useSuspenseQuery` is the **primary** data-fetching hook
|
||||
* No `isLoading` conditionals
|
||||
* No early-return spinners
|
||||
|
||||
### 2. Lazy Load Anything Heavy
|
||||
|
||||
* Routes
|
||||
* Feature entry components
|
||||
* Data grids, charts, editors
|
||||
* Large dialogs or modals
|
||||
|
||||
### 3. Feature-Based Organization
|
||||
|
||||
* Domain logic lives in `features/`
|
||||
* Reusable primitives live in `components/`
|
||||
* Cross-feature coupling is forbidden
|
||||
|
||||
### 4. TypeScript Is Strict
|
||||
|
||||
* No `any`
|
||||
* Explicit return types
|
||||
* `import type` always
|
||||
* Types are first-class design artifacts
|
||||
|
||||
---
|
||||
|
||||
## 3. When to Use This Skill
|
||||
|
||||
Use **frontend-dev-guidelines** when:
|
||||
|
||||
* Creating components or pages
|
||||
* Adding new features
|
||||
* Fetching or mutating data
|
||||
* Setting up routing
|
||||
* Styling with MUI
|
||||
* Addressing performance issues
|
||||
* Reviewing or refactoring frontend code
|
||||
|
||||
---
|
||||
|
||||
## 4. Quick Start Checklists
|
||||
|
||||
### New Component Checklist
|
||||
|
||||
Creating a component? Follow this checklist:
|
||||
* [ ] `React.FC<Props>` with explicit props interface
|
||||
* [ ] Lazy loaded if non-trivial
|
||||
* [ ] Wrapped in `<SuspenseLoader>`
|
||||
* [ ] Uses `useSuspenseQuery` for data
|
||||
* [ ] No early returns
|
||||
* [ ] Handlers wrapped in `useCallback`
|
||||
* [ ] Styles inline if <100 lines
|
||||
* [ ] Default export at bottom
|
||||
* [ ] Uses `useMuiSnackbar` for feedback
|
||||
|
||||
- [ ] Use `React.FC<Props>` pattern with TypeScript
|
||||
- [ ] Lazy load if heavy component: `React.lazy(() => import())`
|
||||
- [ ] Wrap in `<SuspenseLoader>` for loading states
|
||||
- [ ] Use `useSuspenseQuery` for data fetching
|
||||
- [ ] Import aliases: `@/`, `~types`, `~components`, `~features`
|
||||
- [ ] Styles: Inline if <100 lines, separate file if >100 lines
|
||||
- [ ] Use `useCallback` for event handlers passed to children
|
||||
- [ ] Default export at bottom
|
||||
- [ ] No early returns with loading spinners
|
||||
- [ ] Use `useMuiSnackbar` for user notifications
|
||||
---
|
||||
|
||||
### New Feature Checklist
|
||||
|
||||
Creating a feature? Set up this structure:
|
||||
|
||||
- [ ] Create `features/{feature-name}/` directory
|
||||
- [ ] Create subdirectories: `api/`, `components/`, `hooks/`, `helpers/`, `types/`
|
||||
- [ ] Create API service file: `api/{feature}Api.ts`
|
||||
- [ ] Set up TypeScript types in `types/`
|
||||
- [ ] Create route in `routes/{feature-name}/index.tsx`
|
||||
- [ ] Lazy load feature components
|
||||
- [ ] Use Suspense boundaries
|
||||
- [ ] Export public API from feature `index.ts`
|
||||
* [ ] Create `features/{feature-name}/`
|
||||
* [ ] Subdirs: `api/`, `components/`, `hooks/`, `helpers/`, `types/`
|
||||
* [ ] API layer isolated in `api/`
|
||||
* [ ] Public exports via `index.ts`
|
||||
* [ ] Feature entry lazy loaded
|
||||
* [ ] Suspense boundary at feature level
|
||||
* [ ] Route defined under `routes/`
|
||||
|
||||
---
|
||||
|
||||
## Import Aliases Quick Reference
|
||||
## 5. Import Aliases (Required)
|
||||
|
||||
| Alias | Resolves To | Example |
|
||||
|-------|-------------|---------|
|
||||
| `@/` | `src/` | `import { apiClient } from '@/lib/apiClient'` |
|
||||
| `~types` | `src/types` | `import type { User } from '~types/user'` |
|
||||
| `~components` | `src/components` | `import { SuspenseLoader } from '~components/SuspenseLoader'` |
|
||||
| `~features` | `src/features` | `import { authApi } from '~features/auth'` |
|
||||
| Alias | Path |
|
||||
| ------------- | ---------------- |
|
||||
| `@/` | `src/` |
|
||||
| `~types` | `src/types` |
|
||||
| `~components` | `src/components` |
|
||||
| `~features` | `src/features` |
|
||||
|
||||
Defined in: [vite.config.ts](../../vite.config.ts) lines 180-185
|
||||
Aliases must be used consistently. Relative imports beyond one level are discouraged.
|
||||
|
||||
---
|
||||
|
||||
## Common Imports Cheatsheet
|
||||
## 6. Component Standards
|
||||
|
||||
```typescript
|
||||
// React & Lazy Loading
|
||||
import React, { useState, useCallback, useMemo } from 'react';
|
||||
const Heavy = React.lazy(() => import('./Heavy'));
|
||||
### Required Structure Order
|
||||
|
||||
// MUI Components
|
||||
import { Box, Paper, Typography, Button, Grid } from '@mui/material';
|
||||
import type { SxProps, Theme } from '@mui/material';
|
||||
1. Types / Props
|
||||
2. Hooks
|
||||
3. Derived values (`useMemo`)
|
||||
4. Handlers (`useCallback`)
|
||||
5. Render
|
||||
6. Default export
|
||||
|
||||
// TanStack Query (Suspense)
|
||||
import { useSuspenseQuery, useQueryClient } from '@tanstack/react-query';
|
||||
### Lazy Loading Pattern
|
||||
|
||||
// TanStack Router
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
|
||||
// Project Components
|
||||
import { SuspenseLoader } from '~components/SuspenseLoader';
|
||||
|
||||
// Hooks
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useMuiSnackbar } from '@/hooks/useMuiSnackbar';
|
||||
|
||||
// Types
|
||||
import type { Post } from '~types/post';
|
||||
```ts
|
||||
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Topic Guides
|
||||
|
||||
### 🎨 Component Patterns
|
||||
|
||||
**Modern React components use:**
|
||||
- `React.FC<Props>` for type safety
|
||||
- `React.lazy()` for code splitting
|
||||
- `SuspenseLoader` for loading states
|
||||
- Named const + default export pattern
|
||||
|
||||
**Key Concepts:**
|
||||
- Lazy load heavy components (DataGrid, charts, editors)
|
||||
- Always wrap lazy components in Suspense
|
||||
- Use SuspenseLoader component (with fade animation)
|
||||
- Component structure: Props → Hooks → Handlers → Render → Export
|
||||
|
||||
**[📖 Complete Guide: resources/component-patterns.md](resources/component-patterns.md)**
|
||||
Always wrapped in `<SuspenseLoader>`.
|
||||
|
||||
---
|
||||
|
||||
### 📊 Data Fetching
|
||||
## 7. Data Fetching Doctrine
|
||||
|
||||
**PRIMARY PATTERN: useSuspenseQuery**
|
||||
- Use with Suspense boundaries
|
||||
- Cache-first strategy (check grid cache before API)
|
||||
- Replaces `isLoading` checks
|
||||
- Type-safe with generics
|
||||
### Primary Pattern
|
||||
|
||||
**API Service Layer:**
|
||||
- Create `features/{feature}/api/{feature}Api.ts`
|
||||
- Use `apiClient` axios instance
|
||||
- Centralized methods per feature
|
||||
- Route format: `/form/route` (NOT `/api/form/route`)
|
||||
* `useSuspenseQuery`
|
||||
* Cache-first
|
||||
* Typed responses
|
||||
|
||||
**[📖 Complete Guide: resources/data-fetching.md](resources/data-fetching.md)**
|
||||
### Forbidden Patterns
|
||||
|
||||
❌ `isLoading`
|
||||
❌ manual spinners
|
||||
❌ fetch logic inside components
|
||||
❌ API calls without feature API layer
|
||||
|
||||
### API Layer Rules
|
||||
|
||||
* One API file per feature
|
||||
* No inline axios calls
|
||||
* No `/api/` prefix in routes
|
||||
|
||||
---
|
||||
|
||||
### 📁 File Organization
|
||||
## 8. Routing Standards (TanStack Router)
|
||||
|
||||
**features/ vs components/:**
|
||||
- `features/`: Domain-specific (posts, comments, auth)
|
||||
- `components/`: Truly reusable (SuspenseLoader, CustomAppBar)
|
||||
|
||||
**Feature Subdirectories:**
|
||||
```
|
||||
features/
|
||||
my-feature/
|
||||
api/ # API service layer
|
||||
components/ # Feature components
|
||||
hooks/ # Custom hooks
|
||||
helpers/ # Utility functions
|
||||
types/ # TypeScript types
|
||||
```
|
||||
|
||||
**[📖 Complete Guide: resources/file-organization.md](resources/file-organization.md)**
|
||||
|
||||
---
|
||||
|
||||
### 🎨 Styling
|
||||
|
||||
**Inline vs Separate:**
|
||||
- <100 lines: Inline `const styles: Record<string, SxProps<Theme>>`
|
||||
- >100 lines: Separate `.styles.ts` file
|
||||
|
||||
**Primary Method:**
|
||||
- Use `sx` prop for MUI components
|
||||
- Type-safe with `SxProps<Theme>`
|
||||
- Theme access: `(theme) => theme.palette.primary.main`
|
||||
|
||||
**MUI v7 Grid:**
|
||||
```typescript
|
||||
<Grid size={{ xs: 12, md: 6 }}> // ✅ v7 syntax
|
||||
<Grid xs={12} md={6}> // ❌ Old syntax
|
||||
```
|
||||
|
||||
**[📖 Complete Guide: resources/styling-guide.md](resources/styling-guide.md)**
|
||||
|
||||
---
|
||||
|
||||
### 🛣️ Routing
|
||||
|
||||
**TanStack Router - Folder-Based:**
|
||||
- Directory: `routes/my-route/index.tsx`
|
||||
- Lazy load components
|
||||
- Use `createFileRoute`
|
||||
- Breadcrumb data in loader
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { lazy } from 'react';
|
||||
|
||||
const MyPage = lazy(() => import('@/features/my-feature/components/MyPage'));
|
||||
* Folder-based routing only
|
||||
* Lazy load route components
|
||||
* Breadcrumb metadata via loaders
|
||||
|
||||
```ts
|
||||
export const Route = createFileRoute('/my-route/')({
|
||||
component: MyPage,
|
||||
loader: () => ({ crumb: 'My Route' }),
|
||||
component: MyPage,
|
||||
loader: () => ({ crumb: 'My Route' }),
|
||||
});
|
||||
```
|
||||
|
||||
**[📖 Complete Guide: resources/routing-guide.md](resources/routing-guide.md)**
|
||||
|
||||
---
|
||||
|
||||
### ⏳ Loading & Error States
|
||||
## 9. Styling Standards (MUI v7)
|
||||
|
||||
**CRITICAL RULE: No Early Returns**
|
||||
### Inline vs Separate
|
||||
|
||||
```typescript
|
||||
// ❌ NEVER - Causes layout shift
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner />;
|
||||
}
|
||||
* `<100 lines`: inline `sx`
|
||||
* `>100 lines`: `{Component}.styles.ts`
|
||||
|
||||
// ✅ ALWAYS - Consistent layout
|
||||
<SuspenseLoader>
|
||||
<Content />
|
||||
</SuspenseLoader>
|
||||
### Grid Syntax (v7 Only)
|
||||
|
||||
```tsx
|
||||
<Grid size={{ xs: 12, md: 6 }} /> // ✅
|
||||
<Grid xs={12} md={6} /> // ❌
|
||||
```
|
||||
|
||||
**Why:** Prevents Cumulative Layout Shift (CLS), better UX
|
||||
|
||||
**Error Handling:**
|
||||
- Use `useMuiSnackbar` for user feedback
|
||||
- NEVER `react-toastify`
|
||||
- TanStack Query `onError` callbacks
|
||||
|
||||
**[📖 Complete Guide: resources/loading-and-error-states.md](resources/loading-and-error-states.md)**
|
||||
Theme access must always be type-safe.
|
||||
|
||||
---
|
||||
|
||||
### ⚡ Performance
|
||||
## 10. Loading & Error Handling
|
||||
|
||||
**Optimization Patterns:**
|
||||
- `useMemo`: Expensive computations (filter, sort, map)
|
||||
- `useCallback`: Event handlers passed to children
|
||||
- `React.memo`: Expensive components
|
||||
- Debounced search (300-500ms)
|
||||
- Memory leak prevention (cleanup in useEffect)
|
||||
### Absolute Rule
|
||||
|
||||
**[📖 Complete Guide: resources/performance.md](resources/performance.md)**
|
||||
❌ Never return early loaders
|
||||
✅ Always rely on Suspense boundaries
|
||||
|
||||
### User Feedback
|
||||
|
||||
* `useMuiSnackbar` only
|
||||
* No third-party toast libraries
|
||||
|
||||
---
|
||||
|
||||
### 📘 TypeScript
|
||||
## 11. Performance Defaults
|
||||
|
||||
**Standards:**
|
||||
- Strict mode, no `any` type
|
||||
- Explicit return types on functions
|
||||
- Type imports: `import type { User } from '~types/user'`
|
||||
- Component prop interfaces with JSDoc
|
||||
* `useMemo` for expensive derivations
|
||||
* `useCallback` for passed handlers
|
||||
* `React.memo` for heavy pure components
|
||||
* Debounce search (300–500ms)
|
||||
* Cleanup effects to avoid leaks
|
||||
|
||||
**[📖 Complete Guide: resources/typescript-standards.md](resources/typescript-standards.md)**
|
||||
Performance regressions are bugs.
|
||||
|
||||
---
|
||||
|
||||
### 🔧 Common Patterns
|
||||
## 12. TypeScript Standards
|
||||
|
||||
**Covered Topics:**
|
||||
- React Hook Form with Zod validation
|
||||
- DataGrid wrapper contracts
|
||||
- Dialog component standards
|
||||
- `useAuth` hook for current user
|
||||
- Mutation patterns with cache invalidation
|
||||
|
||||
**[📖 Complete Guide: resources/common-patterns.md](resources/common-patterns.md)**
|
||||
* Strict mode enabled
|
||||
* No implicit `any`
|
||||
* Explicit return types
|
||||
* JSDoc on public interfaces
|
||||
* Types colocated with feature
|
||||
|
||||
---
|
||||
|
||||
### 📚 Complete Examples
|
||||
|
||||
**Full working examples:**
|
||||
- Modern component with all patterns
|
||||
- Complete feature structure
|
||||
- API service layer
|
||||
- Route with lazy loading
|
||||
- Suspense + useSuspenseQuery
|
||||
- Form with validation
|
||||
|
||||
**[📖 Complete Guide: resources/complete-examples.md](resources/complete-examples.md)**
|
||||
|
||||
---
|
||||
|
||||
## Navigation Guide
|
||||
|
||||
| Need to... | Read this resource |
|
||||
|------------|-------------------|
|
||||
| Create a component | [component-patterns.md](resources/component-patterns.md) |
|
||||
| Fetch data | [data-fetching.md](resources/data-fetching.md) |
|
||||
| Organize files/folders | [file-organization.md](resources/file-organization.md) |
|
||||
| Style components | [styling-guide.md](resources/styling-guide.md) |
|
||||
| Set up routing | [routing-guide.md](resources/routing-guide.md) |
|
||||
| Handle loading/errors | [loading-and-error-states.md](resources/loading-and-error-states.md) |
|
||||
| Optimize performance | [performance.md](resources/performance.md) |
|
||||
| TypeScript types | [typescript-standards.md](resources/typescript-standards.md) |
|
||||
| Forms/Auth/DataGrid | [common-patterns.md](resources/common-patterns.md) |
|
||||
| See full examples | [complete-examples.md](resources/complete-examples.md) |
|
||||
|
||||
---
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Lazy Load Everything Heavy**: Routes, DataGrid, charts, editors
|
||||
2. **Suspense for Loading**: Use SuspenseLoader, not early returns
|
||||
3. **useSuspenseQuery**: Primary data fetching pattern for new code
|
||||
4. **Features are Organized**: api/, components/, hooks/, helpers/ subdirs
|
||||
5. **Styles Based on Size**: <100 inline, >100 separate
|
||||
6. **Import Aliases**: Use @/, ~types, ~components, ~features
|
||||
7. **No Early Returns**: Prevents layout shift
|
||||
8. **useMuiSnackbar**: For all user notifications
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference: File Structure
|
||||
## 13. Canonical File Structure
|
||||
|
||||
```
|
||||
src/
|
||||
features/
|
||||
my-feature/
|
||||
api/
|
||||
myFeatureApi.ts # API service
|
||||
components/
|
||||
MyFeature.tsx # Main component
|
||||
SubComponent.tsx # Related components
|
||||
hooks/
|
||||
useMyFeature.ts # Custom hooks
|
||||
useSuspenseMyFeature.ts # Suspense hooks
|
||||
helpers/
|
||||
myFeatureHelpers.ts # Utilities
|
||||
types/
|
||||
index.ts # TypeScript types
|
||||
index.ts # Public exports
|
||||
index.ts
|
||||
|
||||
components/
|
||||
SuspenseLoader/
|
||||
SuspenseLoader.tsx # Reusable loader
|
||||
CustomAppBar/
|
||||
CustomAppBar.tsx # Reusable app bar
|
||||
|
||||
routes/
|
||||
my-route/
|
||||
index.tsx # Route component
|
||||
create/
|
||||
index.tsx # Nested route
|
||||
index.tsx
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Modern Component Template (Quick Copy)
|
||||
## 14. Canonical Component Template
|
||||
|
||||
```typescript
|
||||
```ts
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { Box, Paper } from '@mui/material';
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
@@ -356,44 +286,74 @@ import { featureApi } from '../api/featureApi';
|
||||
import type { FeatureData } from '~types/feature';
|
||||
|
||||
interface MyComponentProps {
|
||||
id: number;
|
||||
onAction?: () => void;
|
||||
id: number;
|
||||
onAction?: () => void;
|
||||
}
|
||||
|
||||
export const MyComponent: React.FC<MyComponentProps> = ({ id, onAction }) => {
|
||||
const [state, setState] = useState<string>('');
|
||||
const [state, setState] = useState('');
|
||||
|
||||
const { data } = useSuspenseQuery({
|
||||
queryKey: ['feature', id],
|
||||
queryFn: () => featureApi.getFeature(id),
|
||||
});
|
||||
const { data } = useSuspenseQuery<FeatureData>({
|
||||
queryKey: ['feature', id],
|
||||
queryFn: () => featureApi.getFeature(id),
|
||||
});
|
||||
|
||||
const handleAction = useCallback(() => {
|
||||
setState('updated');
|
||||
onAction?.();
|
||||
}, [onAction]);
|
||||
const handleAction = useCallback(() => {
|
||||
setState('updated');
|
||||
onAction?.();
|
||||
}, [onAction]);
|
||||
|
||||
return (
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Paper sx={{ p: 3 }}>
|
||||
{/* Content */}
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
return (
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Paper sx={{ p: 3 }}>
|
||||
{/* Content */}
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default MyComponent;
|
||||
```
|
||||
|
||||
For complete examples, see [resources/complete-examples.md](resources/complete-examples.md)
|
||||
---
|
||||
|
||||
## 15. Anti-Patterns (Immediate Rejection)
|
||||
|
||||
❌ Early loading returns
|
||||
❌ Feature logic in `components/`
|
||||
❌ Shared state via prop drilling instead of hooks
|
||||
❌ Inline API calls
|
||||
❌ Untyped responses
|
||||
❌ Multiple responsibilities in one component
|
||||
|
||||
---
|
||||
|
||||
## Related Skills
|
||||
## 16. Integration With Other Skills
|
||||
|
||||
- **error-tracking**: Error tracking with Sentry (applies to frontend too)
|
||||
- **backend-dev-guidelines**: Backend API patterns that frontend consumes
|
||||
* **frontend-design** → Visual systems & aesthetics
|
||||
* **page-cro** → Layout hierarchy & conversion logic
|
||||
* **analytics-tracking** → Event instrumentation
|
||||
* **backend-dev-guidelines** → API contract alignment
|
||||
* **error-tracking** → Runtime observability
|
||||
|
||||
---
|
||||
|
||||
**Skill Status**: Modular structure with progressive loading for optimal context management
|
||||
## 17. Operator Validation Checklist
|
||||
|
||||
Before finalizing code:
|
||||
|
||||
* [ ] FFCI ≥ 6
|
||||
* [ ] Suspense used correctly
|
||||
* [ ] Feature boundaries respected
|
||||
* [ ] No early returns
|
||||
* [ ] Types explicit and correct
|
||||
* [ ] Lazy loading applied
|
||||
* [ ] Performance safe
|
||||
|
||||
---
|
||||
|
||||
## 18. Skill Status
|
||||
|
||||
**Status:** Stable, opinionated, and enforceable
|
||||
**Intended Use:** Production React codebases with long-term maintenance horizons
|
||||
|
||||
|
||||
@@ -1,394 +1,284 @@
|
||||
---
|
||||
name: mobile-design
|
||||
description: Mobile-first design thinking and decision-making for iOS and Android apps. Touch interaction, performance patterns, platform conventions. Teaches principles, not fixed values. Use when building React Native, Flutter, or native mobile apps.
|
||||
description: Mobile-first design and engineering doctrine for iOS and Android apps. Covers touch interaction, performance, platform conventions, offline behavior, and mobile-specific decision-making. Teaches principles and constraints, not fixed layouts. Use for React Native, Flutter, or native mobile apps.
|
||||
allowed-tools: Read, Glob, Grep, Bash
|
||||
---
|
||||
|
||||
# Mobile Design System
|
||||
|
||||
**(Mobile-First · Touch-First · Platform-Respectful)**
|
||||
|
||||
> **Philosophy:** Touch-first. Battery-conscious. Platform-respectful. Offline-capable.
|
||||
> **Core Principle:** Mobile is NOT a small desktop. THINK mobile constraints, ASK platform choice.
|
||||
> **Core Law:** Mobile is NOT a small desktop.
|
||||
> **Operating Rule:** Think constraints first, aesthetics second.
|
||||
|
||||
This skill exists to **prevent desktop-thinking, AI-defaults, and unsafe assumptions** when designing or building mobile applications.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Runtime Scripts
|
||||
## 1. Mobile Feasibility & Risk Index (MFRI)
|
||||
|
||||
**Execute these for validation (don't read, just run):**
|
||||
Before designing or implementing **any mobile feature or screen**, assess feasibility.
|
||||
|
||||
| Script | Purpose | Usage |
|
||||
|--------|---------|-------|
|
||||
| `scripts/mobile_audit.py` | Mobile UX & Touch Audit | `python scripts/mobile_audit.py <project_path>` |
|
||||
### MFRI Dimensions (1–5)
|
||||
|
||||
| Dimension | Question |
|
||||
| -------------------------- | ----------------------------------------------------------------- |
|
||||
| **Platform Clarity** | Is the target platform (iOS / Android / both) explicitly defined? |
|
||||
| **Interaction Complexity** | How complex are gestures, flows, or navigation? |
|
||||
| **Performance Risk** | Does this involve lists, animations, heavy state, or media? |
|
||||
| **Offline Dependence** | Does the feature break or degrade without network? |
|
||||
| **Accessibility Risk** | Does this impact motor, visual, or cognitive accessibility? |
|
||||
|
||||
### Score Formula
|
||||
|
||||
```
|
||||
MFRI = (Platform Clarity + Accessibility Readiness)
|
||||
− (Interaction Complexity + Performance Risk + Offline Dependence)
|
||||
```
|
||||
|
||||
**Range:** `-10 → +10`
|
||||
|
||||
### Interpretation
|
||||
|
||||
| MFRI | Meaning | Required Action |
|
||||
| -------- | --------- | ------------------------------------- |
|
||||
| **6–10** | Safe | Proceed normally |
|
||||
| **3–5** | Moderate | Add performance + UX validation |
|
||||
| **0–2** | Risky | Simplify interactions or architecture |
|
||||
| **< 0** | Dangerous | Redesign before implementation |
|
||||
|
||||
---
|
||||
|
||||
## 🔴 MANDATORY: Read Reference Files Before Working!
|
||||
## 2. Mandatory Thinking Before Any Work
|
||||
|
||||
**⛔ DO NOT start development until you read the relevant files:**
|
||||
### ⛔ STOP: Ask Before Assuming (Required)
|
||||
|
||||
### Universal (Always Read)
|
||||
If **any of the following are not explicitly stated**, you MUST ask before proceeding:
|
||||
|
||||
| File | Content | Status |
|
||||
|------|---------|--------|
|
||||
| **[mobile-design-thinking.md](mobile-design-thinking.md)** | **⚠️ ANTI-MEMORIZATION: Forces thinking, prevents AI defaults** | **⬜ CRITICAL FIRST** |
|
||||
| **[touch-psychology.md](touch-psychology.md)** | **Fitts' Law, gestures, haptics, thumb zone** | **⬜ CRITICAL** |
|
||||
| **[mobile-performance.md](mobile-performance.md)** | **RN/Flutter performance, 60fps, memory** | **⬜ CRITICAL** |
|
||||
| **[mobile-backend.md](mobile-backend.md)** | **Push notifications, offline sync, mobile API** | **⬜ CRITICAL** |
|
||||
| **[mobile-testing.md](mobile-testing.md)** | **Testing pyramid, E2E, platform-specific** | **⬜ CRITICAL** |
|
||||
| **[mobile-debugging.md](mobile-debugging.md)** | **Native vs JS debugging, Flipper, Logcat** | **⬜ CRITICAL** |
|
||||
| [mobile-navigation.md](mobile-navigation.md) | Tab/Stack/Drawer, deep linking | ⬜ Read |
|
||||
| [mobile-typography.md](mobile-typography.md) | System fonts, Dynamic Type, a11y | ⬜ Read |
|
||||
| [mobile-color-system.md](mobile-color-system.md) | OLED, dark mode, battery-aware | ⬜ Read |
|
||||
| [decision-trees.md](decision-trees.md) | Framework/state/storage selection | ⬜ Read |
|
||||
| Aspect | Question | Why |
|
||||
| ---------- | ------------------------------------------ | ---------------------------------------- |
|
||||
| Platform | iOS, Android, or both? | Affects navigation, gestures, typography |
|
||||
| Framework | React Native, Flutter, or native? | Determines performance and patterns |
|
||||
| Navigation | Tabs, stack, drawer? | Core UX architecture |
|
||||
| Offline | Must it work offline? | Data & sync strategy |
|
||||
| Devices | Phone only or tablet too? | Layout & density rules |
|
||||
| Audience | Consumer, enterprise, accessibility needs? | Touch & readability |
|
||||
|
||||
> 🧠 **mobile-design-thinking.md is PRIORITY!** This file ensures AI thinks instead of using memorized patterns.
|
||||
|
||||
### Platform-Specific (Read Based on Target)
|
||||
|
||||
| Platform | File | Content | When to Read |
|
||||
|----------|------|---------|--------------|
|
||||
| **iOS** | [platform-ios.md](platform-ios.md) | Human Interface Guidelines, SF Pro, SwiftUI patterns | Building for iPhone/iPad |
|
||||
| **Android** | [platform-android.md](platform-android.md) | Material Design 3, Roboto, Compose patterns | Building for Android |
|
||||
| **Cross-Platform** | Both above | Platform divergence points | React Native / Flutter |
|
||||
|
||||
> 🔴 **If building for iOS → Read platform-ios.md FIRST!**
|
||||
> 🔴 **If building for Android → Read platform-android.md FIRST!**
|
||||
> 🔴 **If cross-platform → Read BOTH and apply conditional platform logic!**
|
||||
🚫 **Never default to your favorite stack or pattern.**
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ CRITICAL: ASK BEFORE ASSUMING (MANDATORY)
|
||||
## 3. Mandatory Reference Reading (Enforced)
|
||||
|
||||
> **STOP! If the user's request is open-ended, DO NOT default to your favorites.**
|
||||
### Universal (Always Read First)
|
||||
|
||||
### You MUST Ask If Not Specified:
|
||||
| File | Purpose | Status |
|
||||
| ----------------------------- | ---------------------------------- | ----------------- |
|
||||
| **mobile-design-thinking.md** | Anti-memorization, context-forcing | 🔴 REQUIRED FIRST |
|
||||
| **touch-psychology.md** | Fitts’ Law, thumb zones, gestures | 🔴 REQUIRED |
|
||||
| **mobile-performance.md** | 60fps, memory, battery | 🔴 REQUIRED |
|
||||
| **mobile-backend.md** | Offline sync, push, APIs | 🔴 REQUIRED |
|
||||
| **mobile-testing.md** | Device & E2E testing | 🔴 REQUIRED |
|
||||
| **mobile-debugging.md** | Native vs JS debugging | 🔴 REQUIRED |
|
||||
|
||||
| Aspect | Ask | Why |
|
||||
|--------|-----|-----|
|
||||
| **Platform** | "iOS, Android, or both?" | Affects EVERY design decision |
|
||||
| **Framework** | "React Native, Flutter, or native?" | Determines patterns and tools |
|
||||
| **Navigation** | "Tab bar, drawer, or stack-based?" | Core UX decision |
|
||||
| **State** | "What state management? (Zustand/Redux/Riverpod/BLoC?)" | Architecture foundation |
|
||||
| **Offline** | "Does this need to work offline?" | Affects data strategy |
|
||||
| **Target devices** | "Phone only, or tablet support?" | Layout complexity |
|
||||
### Platform-Specific (Conditional)
|
||||
|
||||
### ⛔ AI MOBILE ANTI-PATTERNS (YASAK LİSTESİ)
|
||||
| Platform | File |
|
||||
| -------------- | ------------------- |
|
||||
| iOS | platform-ios.md |
|
||||
| Android | platform-android.md |
|
||||
| Cross-platform | BOTH above |
|
||||
|
||||
> 🚫 **These are AI default tendencies that MUST be avoided!**
|
||||
|
||||
#### Performance Sins
|
||||
|
||||
| ❌ NEVER DO | Why It's Wrong | ✅ ALWAYS DO |
|
||||
|-------------|----------------|--------------|
|
||||
| **ScrollView for long lists** | Renders ALL items, memory explodes | Use `FlatList` / `FlashList` / `ListView.builder` |
|
||||
| **Inline renderItem function** | New function every render, all items re-render | `useCallback` + `React.memo` |
|
||||
| **Missing keyExtractor** | Index-based keys cause bugs on reorder | Unique, stable ID from data |
|
||||
| **Skip getItemLayout** | Async layout = janky scroll | Provide when items have fixed height |
|
||||
| **setState() everywhere** | Unnecessary widget rebuilds | Targeted state, `const` constructors |
|
||||
| **Native driver: false** | Animations blocked by JS thread | `useNativeDriver: true` always |
|
||||
| **console.log in production** | Blocks JS thread severely | Remove before release build |
|
||||
| **Skip React.memo/const** | Every item re-renders on any change | Memoize list items ALWAYS |
|
||||
|
||||
#### Touch/UX Sins
|
||||
|
||||
| ❌ NEVER DO | Why It's Wrong | ✅ ALWAYS DO |
|
||||
|-------------|----------------|--------------|
|
||||
| **Touch target < 44px** | Impossible to tap accurately, frustrating | Minimum 44pt (iOS) / 48dp (Android) |
|
||||
| **Spacing < 8px between targets** | Accidental taps on neighbors | Minimum 8-12px gap |
|
||||
| **Gesture-only interactions** | Motor impaired users excluded | Always provide button alternative |
|
||||
| **No loading state** | User thinks app crashed | ALWAYS show loading feedback |
|
||||
| **No error state** | User stuck, no recovery path | Show error with retry option |
|
||||
| **No offline handling** | Crash/block when network lost | Graceful degradation, cached data |
|
||||
| **Ignore platform conventions** | Users confused, muscle memory broken | iOS feels iOS, Android feels Android |
|
||||
|
||||
#### Security Sins
|
||||
|
||||
| ❌ NEVER DO | Why It's Wrong | ✅ ALWAYS DO |
|
||||
|-------------|----------------|--------------|
|
||||
| **Token in AsyncStorage** | Easily accessible, stolen on rooted device | `SecureStore` / `Keychain` / `EncryptedSharedPreferences` |
|
||||
| **Hardcode API keys** | Reverse engineered from APK/IPA | Environment variables, secure storage |
|
||||
| **Skip SSL pinning** | MITM attacks possible | Pin certificates in production |
|
||||
| **Log sensitive data** | Logs can be extracted | Never log tokens, passwords, PII |
|
||||
|
||||
#### Architecture Sins
|
||||
|
||||
| ❌ NEVER DO | Why It's Wrong | ✅ ALWAYS DO |
|
||||
|-------------|----------------|--------------|
|
||||
| **Business logic in UI** | Untestable, unmaintainable | Service layer separation |
|
||||
| **Global state for everything** | Unnecessary re-renders, complexity | Local state default, lift when needed |
|
||||
| **Deep linking as afterthought** | Notifications, shares broken | Plan deep links from day one |
|
||||
| **Skip dispose/cleanup** | Memory leaks, zombie listeners | Clean up subscriptions, timers |
|
||||
> ❌ If you haven’t read the platform file, you are not allowed to design UI.
|
||||
|
||||
---
|
||||
|
||||
## 📱 Platform Decision Matrix
|
||||
## 4. AI Mobile Anti-Patterns (Hard Bans)
|
||||
|
||||
### When to Unify vs Diverge
|
||||
### 🚫 Performance Sins (Non-Negotiable)
|
||||
|
||||
```
|
||||
UNIFY (same on both) DIVERGE (platform-specific)
|
||||
─────────────────── ──────────────────────────
|
||||
Business Logic ✅ Always -
|
||||
Data Layer ✅ Always -
|
||||
Core Features ✅ Always -
|
||||
|
||||
Navigation - ✅ iOS: edge swipe, Android: back button
|
||||
Gestures - ✅ Platform-native feel
|
||||
Icons - ✅ SF Symbols vs Material Icons
|
||||
Date Pickers - ✅ Native pickers feel right
|
||||
Modals/Sheets - ✅ iOS: bottom sheet vs Android: dialog
|
||||
Typography - ✅ SF Pro vs Roboto (or custom)
|
||||
Error Dialogs - ✅ Platform conventions for alerts
|
||||
```
|
||||
|
||||
### Quick Reference: Platform Defaults
|
||||
|
||||
| Element | iOS | Android |
|
||||
|---------|-----|---------|
|
||||
| **Primary Font** | SF Pro / SF Compact | Roboto |
|
||||
| **Min Touch Target** | 44pt × 44pt | 48dp × 48dp |
|
||||
| **Back Navigation** | Edge swipe left | System back button/gesture |
|
||||
| **Bottom Tab Icons** | SF Symbols | Material Symbols |
|
||||
| **Action Sheet** | UIActionSheet from bottom | Bottom Sheet / Dialog |
|
||||
| **Progress** | Spinner | Linear progress (Material) |
|
||||
| **Pull to Refresh** | Native UIRefreshControl | SwipeRefreshLayout |
|
||||
| ❌ Never | Why | ✅ Always |
|
||||
| ------------------------- | -------------------- | --------------------------------------- |
|
||||
| ScrollView for long lists | Memory explosion | FlatList / FlashList / ListView.builder |
|
||||
| Inline renderItem | Re-renders all rows | useCallback + memo |
|
||||
| Index as key | Reorder bugs | Stable ID |
|
||||
| JS-thread animations | Jank | Native driver / GPU |
|
||||
| console.log in prod | JS thread block | Strip logs |
|
||||
| No memoization | Battery + perf drain | React.memo / const widgets |
|
||||
|
||||
---
|
||||
|
||||
## 🧠 Mobile UX Psychology (Quick Reference)
|
||||
### 🚫 Touch & UX Sins
|
||||
|
||||
### Fitts' Law for Touch
|
||||
|
||||
```
|
||||
Desktop: Cursor is precise (1px)
|
||||
Mobile: Finger is imprecise (~7mm contact area)
|
||||
|
||||
→ Touch targets MUST be 44-48px minimum
|
||||
→ Important actions in THUMB ZONE (bottom of screen)
|
||||
→ Destructive actions AWAY from easy reach
|
||||
```
|
||||
|
||||
### Thumb Zone (One-Handed Usage)
|
||||
|
||||
```
|
||||
┌─────────────────────────────┐
|
||||
│ HARD TO REACH │ ← Navigation, menu, back
|
||||
│ (stretch) │
|
||||
├─────────────────────────────┤
|
||||
│ OK TO REACH │ ← Secondary actions
|
||||
│ (natural) │
|
||||
├─────────────────────────────┤
|
||||
│ EASY TO REACH │ ← PRIMARY CTAs, tab bar
|
||||
│ (thumb's natural arc) │ ← Main content interaction
|
||||
└─────────────────────────────┘
|
||||
[ HOME ]
|
||||
```
|
||||
|
||||
### Mobile-Specific Cognitive Load
|
||||
|
||||
| Desktop | Mobile Difference |
|
||||
|---------|-------------------|
|
||||
| Multiple windows | ONE task at a time |
|
||||
| Keyboard shortcuts | Touch gestures |
|
||||
| Hover states | NO hover (tap or nothing) |
|
||||
| Large viewport | Limited space, scroll vertical |
|
||||
| Stable attention | Interrupted constantly |
|
||||
|
||||
For deep dive: [touch-psychology.md](touch-psychology.md)
|
||||
| ❌ Never | Why | ✅ Always |
|
||||
| --------------------- | -------------------- | ----------------- |
|
||||
| Touch <44–48px | Miss taps | Min touch target |
|
||||
| Gesture-only action | Excludes users | Button fallback |
|
||||
| No loading state | Feels broken | Explicit feedback |
|
||||
| No error recovery | Dead end | Retry + message |
|
||||
| Ignore platform norms | Muscle memory broken | iOS ≠ Android |
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Performance Principles (Quick Reference)
|
||||
### 🚫 Security Sins
|
||||
|
||||
### React Native Critical Rules
|
||||
| ❌ Never | Why | ✅ Always |
|
||||
| ---------------------- | ------------------ | ---------------------- |
|
||||
| Tokens in AsyncStorage | Easily stolen | SecureStore / Keychain |
|
||||
| Hardcoded secrets | Reverse engineered | Env + secure storage |
|
||||
| No SSL pinning | MITM risk | Cert pinning |
|
||||
| Log sensitive data | PII leakage | Never log secrets |
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT: Memoized renderItem + React.memo wrapper
|
||||
const ListItem = React.memo(({ item }: { item: Item }) => (
|
||||
<View style={styles.item}>
|
||||
<Text>{item.title}</Text>
|
||||
</View>
|
||||
---
|
||||
|
||||
## 5. Platform Unification vs Divergence Matrix
|
||||
|
||||
```
|
||||
UNIFY DIVERGE
|
||||
────────────────────────── ─────────────────────────
|
||||
Business logic Navigation behavior
|
||||
Data models Gestures
|
||||
API contracts Icons
|
||||
Validation Typography
|
||||
Error semantics Pickers / dialogs
|
||||
```
|
||||
|
||||
### Platform Defaults
|
||||
|
||||
| Element | iOS | Android |
|
||||
| --------- | ------------ | -------------- |
|
||||
| Font | SF Pro | Roboto |
|
||||
| Min touch | 44pt | 48dp |
|
||||
| Back | Edge swipe | System back |
|
||||
| Sheets | Bottom sheet | Dialog / sheet |
|
||||
| Icons | SF Symbols | Material Icons |
|
||||
|
||||
---
|
||||
|
||||
## 6. Mobile UX Psychology (Non-Optional)
|
||||
|
||||
### Fitts’ Law (Touch Reality)
|
||||
|
||||
* Finger ≠ cursor
|
||||
* Accuracy is low
|
||||
* Reach matters more than precision
|
||||
|
||||
**Rules:**
|
||||
|
||||
* Primary CTAs live in **thumb zone**
|
||||
* Destructive actions pushed away
|
||||
* No hover assumptions
|
||||
|
||||
---
|
||||
|
||||
## 7. Performance Doctrine
|
||||
|
||||
### React Native (Required Pattern)
|
||||
|
||||
```ts
|
||||
const Row = React.memo(({ item }) => (
|
||||
<View><Text>{item.title}</Text></View>
|
||||
));
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: Item }) => <ListItem item={item} />,
|
||||
({ item }) => <Row item={item} />,
|
||||
[]
|
||||
);
|
||||
|
||||
// ✅ CORRECT: FlatList with all optimizations
|
||||
<FlatList
|
||||
data={items}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => item.id} // Stable ID, NOT index
|
||||
getItemLayout={(data, index) => ({
|
||||
keyExtractor={(i) => i.id}
|
||||
getItemLayout={(_, i) => ({
|
||||
length: ITEM_HEIGHT,
|
||||
offset: ITEM_HEIGHT * index,
|
||||
index,
|
||||
offset: ITEM_HEIGHT * i,
|
||||
index: i,
|
||||
})}
|
||||
removeClippedSubviews={true}
|
||||
maxToRenderPerBatch={10}
|
||||
windowSize={5}
|
||||
/>
|
||||
```
|
||||
|
||||
### Flutter Critical Rules
|
||||
### Flutter (Required Pattern)
|
||||
|
||||
```dart
|
||||
// ✅ CORRECT: const constructors prevent rebuilds
|
||||
class MyWidget extends StatelessWidget {
|
||||
const MyWidget({super.key}); // CONST!
|
||||
class Item extends StatelessWidget {
|
||||
const Item({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Column( // CONST!
|
||||
children: [
|
||||
Text('Static content'),
|
||||
MyConstantWidget(),
|
||||
],
|
||||
);
|
||||
return const Text('Static');
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ CORRECT: Targeted state with ValueListenableBuilder
|
||||
ValueListenableBuilder<int>(
|
||||
valueListenable: counter,
|
||||
builder: (context, value, child) => Text('$value'),
|
||||
child: const ExpensiveWidget(), // Won't rebuild!
|
||||
)
|
||||
```
|
||||
|
||||
### Animation Performance
|
||||
|
||||
```
|
||||
GPU-accelerated (FAST): CPU-bound (SLOW):
|
||||
├── transform ├── width, height
|
||||
├── opacity ├── top, left, right, bottom
|
||||
└── (use these ONLY) ├── margin, padding
|
||||
└── (AVOID animating these)
|
||||
```
|
||||
|
||||
For complete guide: [mobile-performance.md](mobile-performance.md)
|
||||
* `const` everywhere possible
|
||||
* Targeted rebuilds only
|
||||
|
||||
---
|
||||
|
||||
## 📝 CHECKPOINT (MANDATORY Before Any Mobile Work)
|
||||
## 8. Mandatory Mobile Checkpoint
|
||||
|
||||
> **Before writing ANY mobile code, you MUST complete this checkpoint:**
|
||||
Before writing **any code**, you must complete this:
|
||||
|
||||
```
|
||||
🧠 CHECKPOINT:
|
||||
🧠 MOBILE CHECKPOINT
|
||||
|
||||
Platform: [ iOS / Android / Both ]
|
||||
Framework: [ React Native / Flutter / SwiftUI / Kotlin ]
|
||||
Files Read: [ List the skill files you've read ]
|
||||
Platform: ___________
|
||||
Framework: ___________
|
||||
Files Read: ___________
|
||||
|
||||
3 Principles I Will Apply:
|
||||
1. _______________
|
||||
2. _______________
|
||||
3. _______________
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
Anti-Patterns I Will Avoid:
|
||||
1. _______________
|
||||
2. _______________
|
||||
1.
|
||||
2.
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```
|
||||
🧠 CHECKPOINT:
|
||||
|
||||
Platform: iOS + Android (Cross-platform)
|
||||
Framework: React Native + Expo
|
||||
Files Read: touch-psychology.md, mobile-performance.md, platform-ios.md, platform-android.md
|
||||
|
||||
3 Principles I Will Apply:
|
||||
1. FlatList with React.memo + useCallback for all lists
|
||||
2. 48px touch targets, thumb zone for primary CTAs
|
||||
3. Platform-specific navigation (edge swipe iOS, back button Android)
|
||||
|
||||
Anti-Patterns I Will Avoid:
|
||||
1. ScrollView for lists → FlatList
|
||||
2. Inline renderItem → Memoized
|
||||
3. AsyncStorage for tokens → SecureStore
|
||||
```
|
||||
|
||||
> 🔴 **Can't fill the checkpoint? → GO BACK AND READ THE SKILL FILES.**
|
||||
❌ Cannot complete → go back and read.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Framework Decision Tree
|
||||
## 9. Framework Decision Tree (Canonical)
|
||||
|
||||
```
|
||||
WHAT ARE YOU BUILDING?
|
||||
│
|
||||
├── Need OTA updates + rapid iteration + web team
|
||||
│ └── ✅ React Native + Expo
|
||||
│
|
||||
├── Need pixel-perfect custom UI + performance critical
|
||||
│ └── ✅ Flutter
|
||||
│
|
||||
├── Deep native features + single platform focus
|
||||
│ ├── iOS only → SwiftUI
|
||||
│ └── Android only → Kotlin + Jetpack Compose
|
||||
│
|
||||
├── Existing RN codebase + new features
|
||||
│ └── ✅ React Native (bare workflow)
|
||||
│
|
||||
└── Enterprise + existing Flutter codebase
|
||||
└── ✅ Flutter
|
||||
Need OTA + web team → React Native + Expo
|
||||
High-perf UI → Flutter
|
||||
iOS only → SwiftUI
|
||||
Android only → Compose
|
||||
```
|
||||
|
||||
For complete decision trees: [decision-trees.md](decision-trees.md)
|
||||
No debate without justification.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Pre-Development Checklist
|
||||
## 10. Release Readiness Checklist
|
||||
|
||||
### Before Starting ANY Mobile Project
|
||||
### Before Shipping
|
||||
|
||||
- [ ] **Platform confirmed?** (iOS / Android / Both)
|
||||
- [ ] **Framework chosen?** (RN / Flutter / Native)
|
||||
- [ ] **Navigation pattern decided?** (Tabs / Stack / Drawer)
|
||||
- [ ] **State management selected?** (Zustand / Redux / Riverpod / BLoC)
|
||||
- [ ] **Offline requirements known?**
|
||||
- [ ] **Deep linking planned from day one?**
|
||||
- [ ] **Target devices defined?** (Phone / Tablet / Both)
|
||||
|
||||
### Before Every Screen
|
||||
|
||||
- [ ] **Touch targets ≥ 44-48px?**
|
||||
- [ ] **Primary CTA in thumb zone?**
|
||||
- [ ] **Loading state exists?**
|
||||
- [ ] **Error state with retry exists?**
|
||||
- [ ] **Offline handling considered?**
|
||||
- [ ] **Platform conventions followed?**
|
||||
|
||||
### Before Release
|
||||
|
||||
- [ ] **console.log removed?**
|
||||
- [ ] **SecureStore for sensitive data?**
|
||||
- [ ] **SSL pinning enabled?**
|
||||
- [ ] **Lists optimized (memo, keyExtractor)?**
|
||||
- [ ] **Memory cleanup on unmount?**
|
||||
- [ ] **Tested on low-end devices?**
|
||||
- [ ] **Accessibility labels on all interactive elements?**
|
||||
* [ ] Touch targets ≥ 44–48px
|
||||
* [ ] Offline handled
|
||||
* [ ] Secure storage used
|
||||
* [ ] Lists optimized
|
||||
* [ ] Logs stripped
|
||||
* [ ] Tested on low-end devices
|
||||
* [ ] Accessibility labels present
|
||||
* [ ] MFRI ≥ 3
|
||||
|
||||
---
|
||||
|
||||
## 📚 Reference Files
|
||||
## 11. Related Skills
|
||||
|
||||
For deeper guidance on specific areas:
|
||||
|
||||
| File | When to Use |
|
||||
|------|-------------|
|
||||
| [mobile-design-thinking.md](mobile-design-thinking.md) | **FIRST! Anti-memorization, forces context-based thinking** |
|
||||
| [touch-psychology.md](touch-psychology.md) | Understanding touch interaction, Fitts' Law, gesture design |
|
||||
| [mobile-performance.md](mobile-performance.md) | Optimizing RN/Flutter, 60fps, memory/battery |
|
||||
| [platform-ios.md](platform-ios.md) | iOS-specific design, HIG compliance |
|
||||
| [platform-android.md](platform-android.md) | Android-specific design, Material Design 3 |
|
||||
| [mobile-navigation.md](mobile-navigation.md) | Navigation patterns, deep linking |
|
||||
| [mobile-typography.md](mobile-typography.md) | Type scale, system fonts, accessibility |
|
||||
| [mobile-color-system.md](mobile-color-system.md) | OLED optimization, dark mode, battery |
|
||||
| [decision-trees.md](decision-trees.md) | Framework, state, storage decisions |
|
||||
* **frontend-design** – Visual systems & components
|
||||
* **frontend-dev-guidelines** – RN/TS architecture
|
||||
* **backend-dev-guidelines** – Mobile-safe APIs
|
||||
* **error-tracking** – Crash & performance telemetry
|
||||
|
||||
---
|
||||
|
||||
> **Remember:** Mobile users are impatient, interrupted, and using imprecise fingers on small screens. Design for the WORST conditions: bad network, one hand, bright sun, low battery. If it works there, it works everywhere.
|
||||
> **Final Law:**
|
||||
> Mobile users are distracted, interrupted, and impatient—often using one hand on a bad network with low battery.
|
||||
> **Design for that reality, or your app will fail quietly.**
|
||||
|
||||
---
|
||||
|
||||
Reference in New Issue
Block a user