NutriCalc Development Guide
Development instructions for NutriCalc - an advanced nutrition calculator for cannabis growing built as a React SPA with TypeScript, Vite, and Tailwind CSS. Features precise nutrient calculations, AI-assisted consultation via Google Gemini API, and comprehensive fertilizer and water management.
Tech Stack
**Frontend**: React 18 + TypeScript + Tailwind CSS**Build Tool**: Vite 4.x**Testing**: Vitest + Playwright + Testing Library**Linting**: ESLint + Prettier**API Integration**: Google Generative AI (@google/generative-ai)**Icons**: Lucide React**Package Manager**: npmInstructions for AI Agent
When working on NutriCalc, follow these guidelines:
1. Code Quality Standards
**TypeScript Requirements:**
Use strict mode enabled, no `any` typesDefine proper interfaces for all components and functionsUse type inference where appropriate but be explicit for public APIs**Component Structure:**
Use functional components with hooks only (no class components)Follow PascalCase for components, camelCase for functions/variables, UPPER_SNAKE_CASE for constantsOrganize: Components in `components/`, utilities in `utils/`, types in `types/`Use absolute imports with `@/` prefixGroup imports: React first, then libraries, then local imports**Error Handling:**
Always handle errors gracefully with user feedback via toast notificationsLog errors appropriately but never leave console.log in production code**Accessibility:**
Add ARIA labels to all interactive elementsEnsure keyboard navigation worksManage focus properlyUse semantic HTML elements2. Project Structure
```
src/
├── components/ # React components (tabs, UI elements)
├── contexts/ # React contexts (Theme, Toast, Water, DataPersistence)
├── hooks/ # Custom hooks (useApiKey, useAppSettings, etc.)
├── types/ # TypeScript type definitions
├── utils/ # Utility functions (calculateNutrients, etc.)
├── constants/ # Configuration constants and data
└── styles/ # CSS styles
```
3. Development Commands
Start dev server: `npm start` (runs on port 3002)
Build production: `npm run build`
Run tests: `npm test`
E2E tests: `npx playwright test`
Lint: `npm run lint`
Type check: `npm run type-check`
4. Performance Guidelines
Use React.memo for expensive componentsImplement useCallback for event handlers passed to childrenUse useMemo for expensive calculationsLazy load components where appropriateCheck bundle size regularly5. Testing Requirements
Write unit tests for all utility functions (>90% coverage target)Add component tests for critical user flows (>80% coverage target)Create E2E tests for main application featuresUse descriptive test names with arrange-act-assert pattern6. Security Best Practices
Never expose API keys in client code (use settings management)Validate all user inputsSanitize data before renderingUse HTTPS for all external API callsRun `npm audit` regularly7. Git Workflow
Use conventional commits: `feat:`, `fix:`, `docs:`, `style:`, `refactor:`, `test:`Create feature branches from mainSquash commits before mergingInclude co-author attribution: `Co-Authored-By: Claude <[email protected]>`Never commit secrets, node_modules, or build artifacts8. Key Components to Know
**SetupTab**: Water amount, growth phase, water type configuration**FertilizerTab**: Fertilizer database management (CRUD)**AnalysisTab**: Nutrient visualization and optimization recommendations**MixingAssistant**: Interactive mixing assistant with live calculations**ChatBar**: AI helper integration (Google Gemini)9. State Management Contexts
**ThemeContext**: Dark/Light Mode**ToastContext**: Notifications**WaterContext**: Water mixture management**DataPersistenceContext**: LocalStorage data persistence10. Pre-Development Checklist
Before making changes:
Run `npm run type-check` - ensure no TypeScript errorsRun `npm run lint` - ensure no ESLint warnings/errorsRun `npm test` - ensure all tests passingCheck for console.log: `grep -r "console\." src/`Verify accessibility requirements11. Pre-Commit Checklist
Before committing:
All new components have proper TypeScript interfacesNew utility functions have unit testsNo hardcoded colors (use Tailwind design system)Proper error handling implementedARIA labels on interactive elementsNo security issues (API keys, XSS vulnerabilities)12. Common Tasks
**Adding new fertilizers**: Update `constants/index.ts` BASE_FERTILIZER_DATABASE
**New components**: Follow existing patterns in `components/` folder, create index.tsx with proper TypeScript types
**State updates**: Use appropriate context or local state
**Testing**: Add unit tests for utilities, update E2E tests for new features
**Styling**: Use Tailwind classes, follow mobile-first responsive patterns
13. Debugging
Common issues:
**Dev Server Issues**: Check Node.js version (requires 20.19.0+ for Vite 7.x)**Build Errors**: Run `npm run type-check` for TypeScript issues**Dependency Problems**: Clear `node_modules` and reinstall**Slow Performance**: Check React DevTools Profiler, reduce re-renders14. Deployment Checklist
Before deploying:
All tests passing (`npm test && npx playwright test`)Type checking clean (`npm run type-check`)Linting clean (`npm run lint`)No console.log statements in production codeBundle size optimizedPerformance audit with LighthouseSecurity audit (`npm audit`)Accessibility testing completedExamples
Creating a New Component
```typescript
import React from 'react';
interface NewComponentProps {
title: string;
onClick: () => void;
}
const NewComponent: React.FC<NewComponentProps> = ({ title, onClick }) => {
return (
<button
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
onClick={onClick}
aria-label={title}
>
{title}
</button>
);
};
export default NewComponent;
```
Writing a Utility Test
```typescript
import { describe, it, expect } from 'vitest';
import { calculateNutrients } from './calculateNutrients';
describe('calculateNutrients', () => {
it('should calculate NPK values correctly', () => {
const result = calculateNutrients({ /* params */ });
expect(result.npk).toEqual({ n: 100, p: 50, k: 75 });
});
});
```
Constraints
Development server runs on port 3002 onlyNode.js version 20.19.0+ requiredGoogle Gemini API key required for AI featuresLocalStorage used for persistence (no backend database)Mobile-first responsive design requiredDark mode support mandatory