Skip to content

Claude/migrate to react native 0154n2 a9 ma39z4xi73h5 sy6j#114

Open
hughesjs wants to merge 25 commits intomasterfrom
claude/migrate-to-react-native-0154n2A9MA39z4xi73h5Sy6j
Open

Claude/migrate to react native 0154n2 a9 ma39z4xi73h5 sy6j#114
hughesjs wants to merge 25 commits intomasterfrom
claude/migrate-to-react-native-0154n2A9MA39z4xi73h5Sy6j

Conversation

@hughesjs
Copy link
Copy Markdown
Owner

No description provided.

Replace Flutter codebase with React Native + TypeScript setup:
- Configure TypeScript with strict mode
- Set up Jest for testing with React Native Testing Library
- Add basic App component with passing tests
- Update README with React Native build instructions
Add core data models matching original Flutter implementation:
- TreadmillData: Real-time workout metrics with FTMS byte parsing
- SupportedSpeedRange: Device speed limits with parsing and validation
- SpeedState: Current speed state with range helpers
- WorkoutState: Workout lifecycle enum (idle/running/paused)
- CompletedWorkout: Saved workout with calorie calculation
- DeviceDescriptor: BLE device info with sorting/comparison

All models use strict TypeScript types (no 'any') and include:
- 96 unit tests covering all functionality
- Helper functions for parsing, formatting, and validation
- Proper readonly interfaces for immutability
Add complete BLE service abstraction:
- BleService interface for platform-agnostic BLE operations
- BleServiceImpl using react-native-ble-plx for real devices
- MockBleService for testing/development without hardware
- FTMS constants (UUIDs, opcodes, result codes)
- Command builders for all FTMS control point operations
- Strongly-typed Bluetooth/connection state management

Features:
- Device scanning with FTMS service filter
- Connect/disconnect with state callbacks
- Treadmill data streaming subscription
- Speed range reading
- Control commands (start, stop, pause, speed)

Includes 45 new tests for BLE layer.
Add database abstraction for storing completed workouts:
- WorkoutRepository interface for data access operations
- SQLiteWorkoutRepository using react-native-sqlite-storage
- MockWorkoutRepository for testing
- Type-safe row conversion with DatabaseTypes

Features:
- CRUD operations for workouts
- Automatic sorting by completion date
- Index on completed_at for performance
- Proper date serialization (ISO strings)

Includes 23 new tests for database layer.
Add context providers for application state:
- BleContext: Bluetooth connection, scanning, device control
- WorkoutContext: Workout lifecycle (start/pause/stop/resume)
- WorkoutHistoryContext: Completed workouts list management

Features:
- BleProvider integrates with BleService for all BLE operations
- WorkoutProvider manages workout state machine and saves completed workouts
- WorkoutHistoryProvider loads/refreshes workout list from repository
- All contexts provide typed hooks (useBle, useWorkout, useWorkoutHistory)
- Callbacks for workout completion events

Includes 20 new tests for context providers.
Add UI components for device discovery and connection:
- DeviceListItem: Shows device name, address, signal strength
- ScanningIndicator: Activity indicator during BLE scanning
- BluetoothWarning: Warning banner for Bluetooth issues
- DeviceSelectionScreen: Full screen for device scanning/selection

Features:
- Auto-starts scanning when Bluetooth is ready
- Sorts devices by signal strength
- Shows connection progress per device
- Handles Bluetooth disabled/unauthorized states
- Error message display

Includes 13 new component tests.
Add the main control screen for interacting with fitness machines:
- WorkoutStatusPanel: Displays distance, time, steps, and calories
- SpeedIndicator: Shows current speed with progress bar and +/- controls
- TreadmillControls: Start/Pause/Resume/Stop buttons based on workout state
- ControlScreen: Main screen integrating all components with BLE and workout context
- Export BleContext and WorkoutContext for testing
- 244 tests passing
Add screen for viewing completed workout history:
- WorkoutHistoryItem: Displays a single workout with stats and delete option
- EmptyHistoryState: Shows message when no workouts exist
- WorkoutHistoryScreen: Main screen with FlatList, pull-to-refresh, delete all
- Export WorkoutHistoryContext and type for testing
- 275 tests passing
Add React Navigation with tab navigator and device selection modal:
- Install @react-navigation/native, bottom-tabs, native-stack
- Add navigation types with strict TypeScript
- Add MainTabNavigator with Control and History tabs
- Add RootNavigator with device selection modal
- Update App.tsx with providers and initialization
- Add navigation tests
- 281 tests passing
Add abstraction layer for health platform integration:
- Add HealthTypes with enums for platforms, auth status, data types
- Add HealthService interface for health platform operations
- Add MockHealthService for testing
- Add comprehensive tests for health service
- Ready for HealthKit/Google Fit implementations
- All tests passing
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 26, 2025

Important

Review skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

121 files out of 229 files are above the max files limit of 100. Please upgrade to Pro plan to get higher limits.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/migrate-to-react-native-0154n2A9MA39z4xi73h5Sy6j

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

claude and others added 15 commits November 26, 2025 11:27
- Add react-native-ci.yml with lint, typecheck, test, and build jobs
- Update dependabot.yml to use npm instead of pub
- Remove obsolete flutter-ci.yml
- React Native 0.76.9 requires @types/react@^18.2.6
- Downgraded @types/react from 19.2.7 to 18.2.6
- Downgraded @types/react-test-renderer from 19.1.0 to 18.3.0
- All 288 tests passing
- Skip native builds if android/ios directories don't exist yet
- This allows CI to pass for TypeScript/tests without native setup
- Builds will run automatically once native directories are added
Phase 1: Critical Issues
- Move service singletons from module scope to component (useMemo)
- Replace useState with useRef for BLE unsubscribe functions
- Add warning when speed range read fails

Changes:
1. App.tsx: Services now instantiated inside component lifecycle
   - Enables proper testing and mocking
   - Prevents hot-reload issues
   - Better cleanup on unmount

2. BleContext.tsx: useRef for treadmillDataUnsubscribeRef
   - Prevents memory leak from function in state
   - Immediate availability (no setState delay)
   - Removes unnecessary re-renders

3. BleContext.tsx: Speed range failure handling
   - Logs warning and shows user error
   - Prevents silent failures with invalid speed commands

All 309 tests passing
Phase 2: High Priority Issues
- Fix deviceSubscription not being cleaned up in disconnect()
- Clean up deviceSubscription in onDisconnected callback
- Remove old subscription before creating new one

Changes:
1. BleServiceImpl.ts: disconnect() now removes deviceSubscription
2. BleServiceImpl.ts: onDisconnected callback removes subscription
3. BleServiceImpl.ts: Remove existing subscription before creating new one

Prevents memory leaks from uncleaned BLE subscriptions
All 309 tests passing
Phase 1.1: Test Quality Improvements
- Refactor WorkoutContext tests to use renderHook
- Refactor WorkoutHistoryContext tests to use renderHook
- Remove manual TestConsumer component pattern
- Cleaner, more maintainable test code
- Tests behaviour not implementation details

Changes:
- WorkoutContext.test.tsx: 13 tests, simplified from 260 to 238 lines
- WorkoutHistoryContext.test.tsx: 7 tests, simplified from 190 to 170 lines
- More idiomatic React testing patterns
- Better test isolation

All 309 tests passing
Added defensive input validation to TreadmillData parsing:
- Created validation rules with sensible max bounds (30 km/h speed, 86400s time, etc.)
- Added validateAndClamp() helper to handle NaN, Infinity, and out-of-bounds values
- Applied validation to all parsed fields: speed, distance, time, calories, steps
- Logs warnings when clamping occurs for debugging

Added performance optimisation to DeviceSelectionScreen:
- Memoised sortDevicesBySignal() to prevent unnecessary re-sorting on every render
- Only re-sorts when discoveredDevices array changes

All 321 tests passing (309 original + 12 new validation tests).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…prevention

Added comprehensive error handling to ControlScreen:
- Wrapped all async operations (start, pause, resume, stop, speed changes, disconnect) in try-catch blocks
- Added console logging for debugging failed operations
- Prevents unhandled promise rejections from crashing the app

Added connection timeouts to BleServiceImpl:
- 30 second timeout for device connection
- 15 second timeout for service discovery
- Created withTimeout() helper to wrap promises with timeout logic
- Provides clear timeout error messages

Added race condition prevention to speed controls:
- Used ref to track if a speed change operation is in progress
- Ignores additional speed button presses while an operation is pending
- Prevents multiple simultaneous speed commands from conflicting

All 321 tests passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Created comprehensive test suite for BleContext covering:
- Initialization and Bluetooth state management
- Device scanning (start, stop, discovery)
- Device connection and speed range reading
- Treadmill data subscription after connection
- Device disconnection and state reset
- Control commands (request control, start, pause, stop, set speed)
- Error handling and error clearing

17 new tests added, bringing total from 321 to 338 tests passing.
Tests cover all major BleContext functionality and integration with BLE service.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Created comprehensive test suite for DeviceSelectionScreen covering:
- Initialization and automatic scan start
- Bluetooth warnings for PoweredOff and Unauthorized states
- Scanning indicator display
- Device list rendering and empty states
- Device sorting by signal strength
- Device connection flow and callbacks
- Connection failure handling
- Error message display
- Scan button toggle (start/stop)
- Cancel button functionality

27 new tests added, bringing total from 338 to 365 tests passing.
All tests verify behaviour rather than implementation details.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Added transaction wrapper to SQLiteWorkoutRepository:
- Created executeInTransaction() helper method that handles BEGIN/COMMIT/ROLLBACK
- Automatically rolls back on errors to maintain database integrity
- Updated saveWorkout() to use transaction wrapper
- Provides foundation for future complex multi-statement operations

Benefits:
- Atomicity: All operations succeed or all fail
- Consistency: Prevents partial database updates on errors
- Extensibility: Easy to wrap future multi-step operations in transactions

All 365 tests passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Implemented comprehensive error handling system with:
- ErrorService: Centralised error logging with severity levels
- ErrorBoundary: React error boundary component to catch component errors
- ErrorContext: App-wide error state management with React Context
- Integrated into App.tsx with proper provider/boundary wrapping
- Added 38 new tests (18 ErrorService, 10 ErrorBoundary, 10 ErrorContext)
- All 403 tests passing

Error handling features:
- Four severity levels (Low, Medium, High, Critical)
- Error callback subscription system
- Max 50 stored errors with automatic trimming
- Error dismissal and clearing
- Custom fallback UI support in ErrorBoundary
- Development vs production error display modes
- Automatic logging of React component errors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Addressed critical and high-severity issues identified in code review:

**Error Handling:**
- Fixed empty catch block in BleServiceImpl.disconnect - now logs warnings
- Added ErrorService integration to all ControlScreen error handlers
- Added async error handling in WorkoutHistoryContext useEffect

**Memory Leaks:**
- Added workoutRepository.close() cleanup in App.tsx
- Added mounted flag check in DeviceSelectionScreen to prevent state updates after unmount

**Code Quality:**
- Replaced deprecated substr() with substring() in 2 locations
- All error handlers now use ErrorService for consistent error tracking

All 403 tests passing. Changes improve error visibility, prevent memory leaks,
and modernise deprecated API usage.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Removed files that should not be in version control:
- .claude/settings.local.json (Claude Code local settings)
- .vscode/launch.json (obsolete Flutter debug configs)
- .vscode/settings.json (obsolete Dart/Flutter settings)

Updated .gitignore for React Native project:
- Added .claude/ directory for Claude Code
- Added React Native specific patterns (.expo-shared, bundles, etc.)
- Added environment files (.env, .env.local)
- Added additional IDE patterns (.sublime-*, .project, .classpath)
- Added gradle and assets directories for Android
- Improved organisation and completeness for React Native development

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fixed all TypeScript compilation errors identified by CI:

**Test Type Safety:**
- Added non-null assertions (!) to array access in test files
- ErrorContext.test.tsx: 9 array access fixes
- ErrorService.test.tsx: 6 array access fixes

**Global Type Declarations:**
- Created src/global.d.ts for React Native's __DEV__ global
- Used type assertions (global as any) for test-only __DEV__ manipulation
- Fixes __DEV__ type errors in ErrorBoundary.test.tsx

**Exact Optional Properties:**
- Fixed ErrorService.ts to comply with exactOptionalPropertyTypes
- Used conditional spread to only include defined optional properties
- Prevents assigning undefined to optional properties

All 403 tests passing. TypeScript strict mode compliance verified.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants