Contributing to SparkyFitness

We welcome contributions of all kinds! Whether you're fixing bugs, adding features, improving documentation, or helping other users, your contributions make SparkyFitness better for everyone.

Quick Start

# Fork and clone the repository
git clone https://github.com/CodeWithCJ/SparkyFitness.git
cd SparkyFitness

# Copy environment template
cp docker/.env.example .env

# Start development environment
./docker/docker-helper.sh dev up

Development Workflow

Setting Up Your Development Environment

  1. Fork the repository on GitHub
  2. Clone your fork locally:
    git clone https://github.com/YOUR_USERNAME/SparkyFitness.git
    cd SparkyFitness
    
  3. Add the upstream remote:
    git remote add upstream https://github.com/CodeWithCJ/SparkyFitness.git
    
  4. Set up your development environment using our Getting Started Guide

Development Process

Branch Management

  • Main Branch: The main branch contains the latest stable code
  • Feature Branches: Create feature branches from main for new work
  • Naming Convention: Use descriptive branch names like feature/add-exercise-tracking or fix/login-validation

Making Changes

  1. Create a feature branch from main:
    git checkout main
    git pull upstream main
    git checkout -b feature/your-feature-name
    
  2. Make your changes following our coding standards:
    • Follow existing code patterns and conventions
    • Write clear, self-documenting code
    • Add comments for complex logic
    • Ensure your changes don't break existing functionality
  3. Test your changes thoroughly:
    • Test in the development environment
    • Verify both frontend and backend functionality
    • Test edge cases and error scenarios
    • Ensure mobile responsiveness for UI changes
  4. Commit your changes:
    git add .
    git commit -m "feat: add exercise tracking functionality"
    

Coding Standards

General Principles

  • Clean Code: Write self-documenting, readable code
  • DRY (Don't Repeat Yourself): Avoid code duplication
  • SOLID Principles: Follow object-oriented design principles
  • Separation of Concerns: Keep different aspects of the application separate

Frontend Standards (React/TypeScript)

Component Structure

// Use functional components with hooks
const ExampleComponent: React.FC<ExampleProps> = ({ prop1, prop2 }) => {
  // Hooks at the top
  const [state, setState] = useState<StateType>('');
  const { data, isLoading } = useQuery(['key'], fetchFn);
  
  // Event handlers
  const handleSubmit = useCallback((e: React.FormEvent) => {
    e.preventDefault();
    // Handle submission
  }, [dependencies]);
  
  // Early returns for loading/error states
  if (isLoading) return <LoadingSpinner />;
  
  return (
    <div className="component-container">
      {/* Component JSX */}
    </div>
  );
};

TypeScript Guidelines

  • Strict typing: Use TypeScript strictly, avoid any type
  • Interface definitions: Define clear interfaces for props and data
  • Type exports: Export types that are used across components
  • Generic components: Use generics for reusable components

Styling Conventions

  • Tailwind CSS: Use Tailwind utility classes for styling
  • shadcn/ui: Prefer shadcn/ui components over custom components
  • Responsive Design: Use responsive classes (sm:, md:, lg:)
  • Dark Mode: Support both light and dark themes

Backend Standards (Node.js/Express)

TypeScript First

  • New Files: All new backend files must be written in TypeScript
  • Strict Mode: Enable strict TypeScript checking
  • Type Safety: Avoid any type, use proper types and interfaces
  • Existing JavaScript: You may maintain existing JavaScript files as JavaScript. New files must be TypeScript, and conversion is encouraged when adding significant functionality.

Zod Schema Validation

  • Required for New Endpoints: All new API endpoints must define Zod schemas for validation
  • Request Validation: Validate request body, params, and query parameters
  • Response Schemas: Define expected response shapes
  • Error Handling: Use Zod's error formatting for client-friendly validation errors

Example:

import { z } from 'zod';

// Define schemas
const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1),
  password: z.string().min(8)
});

// Use in route
app.post('/api/users', async (req, res) => {
  const validated = createUserSchema.parse(req.body);
  // ... rest of handler
});

Testing Requirements

  • New Endpoints Must Have Tests: All new API endpoints require automated tests
  • Test Coverage: Include happy path, error cases, and edge cases
  • Integration Tests: Test database interactions and external dependencies
  • Run Before PR: Execute pnpm run typecheck && pnpm run lint && pnpm run test and ensure all checks pass

Repository Pattern

// All database operations use repository pattern
const userRepository = {
  async createUser(userData) {
    const client = await pool.connect();
    try {
      await client.query('BEGIN');
      // Database operations
      await client.query('COMMIT');
      return result;
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }
};

API Design

  • RESTful endpoints: Follow REST conventions
  • Consistent responses: Use standard response format
  • Error handling: Implement comprehensive error handling
  • Input validation: Validate all inputs with Zod schemas

Security Practices

  • SQL injection prevention: Use parameterized queries
  • Authentication: Verify JWT tokens on protected routes
  • Input sanitization: Sanitize all user inputs
  • Error messages: Don't expose sensitive information

Database Standards

Migration Guidelines

  • Version control: All schema changes through migrations
  • Backwards compatibility: Ensure migrations don't break existing data
  • Transaction wrapping: Wrap migrations in transactions
  • Rollback scripts: Provide rollback capabilities

Naming Conventions

  • Tables: Snake case, plural (e.g., food_diary_entries)
  • Columns: Snake case (e.g., created_at, user_id)
  • Indexes: Descriptive names (e.g., idx_food_diary_user_date)

Pull Request Process

Before Submitting

  1. Update your branch with the latest changes:
    git checkout main
    git pull upstream main
    git checkout your-feature-branch
    git merge main
    
  2. Run the full test suite:
    # Test the application thoroughly
    ./docker/docker-helper.sh dev up
    # Test your changes manually
    # Run any automated tests
    
  3. Review your changes:
    git diff main...your-feature-branch
    

Pull Request Checklist

  • Branch is up to date with the latest main branch
  • Changes have been tested thoroughly in development environment
  • Code follows project conventions and standards
  • No console errors or warnings introduced
  • Mobile responsiveness verified for UI changes
  • Database migrations included if schema changes
  • Documentation updated if new features or API changes
  • Environment variables documented if new ones added
  • Backend Code Standards (if applicable):
    • New backend files are written in TypeScript
    • New endpoints include Zod schemas for validation
    • New endpoints include automated tests
  • Quality Checks Passed:
    • Frontend: pnpm run validate in SparkyFitnessFrontend/
    • Backend: pnpm run typecheck && pnpm run lint && pnpm run test in SparkyFitnessServer/
    • Mobile: pnpm run lint && pnpm run test:run -- --watchman=false --runInBand in SparkyFitnessMobile/

Submitting Your PR

  1. Push your changes:
    git push origin your-feature-branch
    
  2. Create a Pull Request on GitHub with:
    • Clear title: Concise description of the change
    • Detailed description: What problem does this solve and how?
    • Screenshots: For UI changes, include before/after screenshots
    • Testing notes: How to test the changes
    • Breaking changes: Note any breaking changes
    • Related issues: Reference any related issues (e.g., Fixes #123)

PR Template

## Description
Brief description of changes and the problem they solve.

## Type of Change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update

## Testing
- [ ] Changes have been tested locally
- [ ] No console errors or warnings
- [ ] Mobile responsiveness verified (for UI changes)

## Screenshots (if applicable)
Include screenshots for UI changes.

## Additional Notes
Any additional information or context about the changes.

Review Process

  1. Automated Validation: PR validation workflow checks that required checkboxes are checked
    • Detects Frontend, Backend, Mobile, and UI changes automatically
    • Validates mandatory checkboxes based on change type
    • Posts validation results as a comment on your PR
    • Important: Do not remove checkboxes from the PR template - the validation will fail
  2. Automated Tests: CI tests run for changed components (Frontend, Backend, Mobile)
  3. Code Review: Address feedback from reviewers promptly
  4. Testing: Reviewers will test your changes
  5. Approval: Get approval from maintainers
  6. Merge: Maintainers will merge your PR

Automated PR Validation

Our PR validation workflow automatically checks your submission:

What it validates:

  • ✅ Integrity & License checkbox (MANDATORY for all PRs)
  • ✅ Alignment checkbox (MANDATORY for new features)
  • ✅ Frontend Quality checkbox (MANDATORY for Frontend changes)
  • ✅ Backend Code Quality checkbox (MANDATORY for Backend changes)
  • ✅ Screenshots checkbox (MANDATORY for UI changes)
  • ⚠️ PR type selection (Issue/Feature/Documentation)
  • ⚠️ Linked issue reference
  • ⚠️ Description completeness

How it works:

  1. The workflow runs when you open or edit a PR
  2. It detects which parts of the codebase you changed
  3. It validates that appropriate checkboxes are checked
  4. It posts a comment with validation results and guidance
  5. The PR check will fail if required checkboxes are missing

Common issues:

  • Don't remove checkboxes: Keep all checkboxes in the PR template
  • Check the right boxes: Make sure to check boxes that apply to your changes
  • Backend changes: Must confirm TypeScript, Zod schemas, and tests for new code
  • UI changes: Must include before/after screenshots

After Your PR is Merged

  1. Delete your feature branch:
    git checkout main
    git pull upstream main
    git branch -d your-feature-branch
    git push origin --delete your-feature-branch
    
  2. Update your local main:
    git pull upstream main
    

Types of Contributions

Bug Fixes

  • Report issues: Use GitHub issues to report bugs
  • Provide details: Include steps to reproduce, expected vs actual behavior
  • Include environment: OS, browser, version information
  • Screenshots: Visual bugs should include screenshots

New Features

  • Discuss first: Open an issue to discuss new features before implementing
  • Small increments: Break large features into smaller, reviewable chunks
  • Documentation: Include documentation for new features
  • Tests: Ensure new features are properly tested

Documentation

  • Keep it current: Update documentation when code changes
  • Clear examples: Provide clear examples and use cases
  • User-focused: Write from the user's perspective
  • Technical accuracy: Ensure technical information is accurate

Code Quality

  • Refactoring: Improve code structure and readability
  • Performance: Optimize slow operations
  • Security: Address security vulnerabilities
  • Dependencies: Keep dependencies up to date

Getting Help

Community Support

  • GitHub Issues: Ask questions using GitHub issues
  • Discussions: Use GitHub Discussions for general questions
  • Documentation: Check the documentation first

Maintainer Support

  • Complex Issues: Tag maintainers for complex technical issues
  • Feature Requests: Discuss significant feature requests with maintainers
  • Architecture Questions: Get guidance on architectural decisions

Recognition

Contributors are recognized in several ways:

  • Contributors list: All contributors are listed in the project
  • Release notes: Significant contributions are mentioned in release notes
  • Community recognition: Active contributors may be invited to join the core team

Thank you for contributing to SparkyFitness! Your efforts help make fitness tracking better for everyone.