coding-standards
React 19 and TypeScript coding standards for Portfolio Buddy 2. Use when: writing new components, reviewing code, refactoring, or ensuring consistency. Contains component patterns, TypeScript rules, and best practices.
What this skill does
# Coding Standards - Portfolio Buddy 2
## React 19 Patterns
### Component Structure
```typescript
// Good: Functional component with TypeScript
interface MetricsTableProps {
data: Metric[]
onSelect: (id: string) => void
}
export function MetricsTable({ data, onSelect }: MetricsTableProps) {
// Hooks at top
const [selected, setSelected] = useState<Set<string>>(new Set())
// Derived state with useMemo
const sortedData = useMemo(() =>
data.sort((a, b) => b.sharpe - a.sharpe),
[data]
)
// Event handlers with useCallback
const handleSelect = useCallback((id: string) => {
setSelected(prev => new Set(prev).add(id))
onSelect(id)
}, [onSelect])
// Render
return <div>...</div>
}
```
### Hooks Rules
1. **Only at top level** - No hooks in conditionals or loops
2. **Custom hooks start with `use`** - useMetrics, usePortfolio, useSorting
3. **Dependencies array complete** - All deps in useEffect/useMemo/useCallback
4. **Cleanup on unmount** - Return cleanup function from useEffect
### State Management
**Portfolio Buddy 2 uses PLAIN REACT HOOKS ONLY:**
- **Local UI state** → `useState`
- **Derived state** → `useMemo`
- **Stable callbacks** → `useCallback`
- **DOM/value refs** → `useRef`
**NO global state libraries:**
- ❌ No TanStack Query
- ❌ No Zustand
- ❌ No Redux
- ❌ No Jotai
**Pattern**: Props down, custom hooks for shared logic
```typescript
// State management example
const [files, setFiles] = useState<File[]>([])
const [dateRange, setDateRange] = useState({ start: null, end: null })
// Derived state
const filteredData = useMemo(() =>
filterByDateRange(files, dateRange),
[files, dateRange]
)
// Stable callback
const handleUpload = useCallback((newFile: File) => {
setFiles(prev => [...prev, newFile])
}, [])
```
## TypeScript Standards
### No `any` Types
```typescript
// Bad
const data: any = fetchData()
// Good
interface TradeData {
symbol: string
date: Date
pnl: number
}
const data: TradeData[] = fetchData()
```
**Current Violations (Tech Debt)**:
- usePortfolio.ts: 11 instances (trade/metrics types)
- useMetrics.ts: 4 instances (sort comparisons)
- dataUtils.ts: 1 instance (Metrics interface)
- **Total: 15 violations to fix** (originally 16)
### Strict Null Checks
```typescript
// Bad
const value = data.find(x => x.id === id)
value.name // Could be undefined!
// Good
const value = data.find(x => x.id === id)
if (value) {
value.name // Type-safe
}
// Or with optional chaining
const name = data.find(x => x.id === id)?.name
```
### Type Inference When Obvious
```typescript
// Redundant
const count: number = 5
const name: string = 'Portfolio Buddy'
// Better (TypeScript infers)
const count = 5
const name = 'Portfolio Buddy'
// Explicit when needed
const metrics: Metric[] = [] // Empty array needs type
```
## Component Size Limits
### Max 200 Lines Per Component
When component exceeds 200 lines:
1. Extract sub-components
2. Move logic to custom hooks
3. Extract utilities to utils/
### Current Violations
**⚠️ MUST REFACTOR:**
- **PortfolioSection.tsx**: 591 lines (295% of limit)
- Extract EquityChartSection
- Extract PortfolioStats
- Extract ContractControls
- Keep only orchestration logic
**Should refactor:**
- **App.tsx**: 351 lines (175% of limit)
- Extract sections into components
- **MetricsTable.tsx**: 242 lines (121% of limit)
- Improved from 350 lines, still over limit
### Refactoring Example
```typescript
// Before: 591 lines in PortfolioSection
function PortfolioSection() {
// Contract multiplier logic (50 lines)
// Date filtering logic (40 lines)
// Chart configuration (100 lines)
// Statistics calculation (80 lines)
// Rendering logic (300+ lines)
}
// After: Split into focused pieces
function PortfolioSection() {
const portfolio = usePortfolio(files, dateRange)
const contracts = useContractMultipliers(portfolio.strategies)
return (
<div>
<ContractControls {...contracts} />
<EquityChartSection data={portfolio.equity} />
<PortfolioStats metrics={portfolio.metrics} />
</div>
)
}
```
## File Organization
### Actual Directory Structure
```
src/
├── components/
│ └── [AllComponents].tsx (flat structure, no subdirs)
├── hooks/
│ ├── useContractMultipliers.ts
│ ├── useMetrics.ts
│ ├── usePortfolio.ts
│ └── useSorting.ts
├── utils/
│ └── dataUtils.ts (metric calculations, parsing)
├── App.tsx
└── main.tsx
```
**Note**: No `ui/` or `charts/` subdirectories - components are flat in `components/`
### Naming Conventions
- **Components**: PascalCase - `MetricsTable.tsx`, `CorrelationHeatmap.tsx`
- **Hooks**: camelCase with `use` prefix - `useMetrics.ts`, `useSorting.ts`
- **Utils**: camelCase - `calculateMetrics()`, `parseCSV()`
- **Types/Interfaces**: PascalCase - `interface Metric`, `type Trade`
## Error Handling
### Always Handle Errors
```typescript
// Bad
const data = await supabase.storage.upload(file)
// Good
const { data, error } = await supabase.storage.upload(file)
if (error) {
console.error('Upload failed:', error)
toast.error('Failed to upload file')
return
}
```
### Use Try-Catch for Parsing
```typescript
// CSV parsing with error handling
try {
const parsed = parseCSV(file)
setData(parsed.data)
if (parsed.errors.length > 0) {
setErrors(parsed.errors)
}
} catch (error) {
console.error('Parse error:', error)
toast.error('Invalid CSV format')
}
```
### Error Boundaries
**Current Status**: No error boundaries implemented (tech debt)
**Should add**:
```typescript
<ErrorBoundary fallback={<ErrorMessage />}>
<PortfolioSection />
</ErrorBoundary>
```
## Performance
### Memoization
```typescript
// Expensive calculations
const metrics = useMemo(
() => calculateMetrics(portfolioData, riskFreeRate),
[portfolioData, riskFreeRate]
)
// Large data transformations
const correlationMatrix = useMemo(
() => buildCorrelationMatrix(selectedStrategies),
[selectedStrategies]
)
```
### Callback Stability
```typescript
// Prevent child re-renders
const handleSort = useCallback((column: string) => {
setSortColumn(column)
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc')
}, [])
// Pass stable callback to children
<SortableHeader onSort={handleSort} />
```
### Avoid Premature Optimization
1. Build feature first
2. Measure performance if issues arise
3. Optimize based on profiling data
4. Don't optimize without evidence
## Chart.js Integration
### Pattern for Chart Components
```typescript
import { Line } from 'react-chartjs-2'
import { Chart as ChartJS, registerables } from 'chart.js'
import zoomPlugin from 'chartjs-plugin-zoom'
// Register plugins once
ChartJS.register(...registerables, zoomPlugin)
function EquityChart({ data }: { data: EquityData[] }) {
const chartData = useMemo(() => ({
labels: data.map(d => d.date),
datasets: [{
label: 'Equity',
data: data.map(d => d.value),
borderColor: 'rgb(75, 192, 192)',
}]
}), [data])
const options = useMemo(() => ({
responsive: true,
plugins: {
zoom: { enabled: true }
}
}), [])
return <Line data={chartData} options={options} />
}
```
### Chart Libraries
- ✅ **Use**: Chart.js + react-chartjs-2
- ❌ **Don't use**: Recharts (installed but unused, should remove)
## Testing Standards
### What to Test
- ✅ Critical calculations (Sharpe, Sortino, correlation)
- ✅ Data transformations (CSV parsing, metric calculations)
- ✅ Error states and edge cases
- ✅ Hook return values
- ❌ UI implementation details (className, DOM structure)
- ❌ Third-party library internals
### Test Structure
```typescript
describe('calculateMetrics', () => {
it('calculates Sharpe ratio correctly', () => {
const trades = mockTradeData()
const result = calculateMetrics(trades, 0.02)
expect(result.sharpe).toBeCloseTo(1.5, 2)
})
it('handles empty data gracefully', () => {
const result = calculateMetrics([], 0.02)
expect(result.sharpe).toBe(0)
})
})
```
**Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.