Health Analytics & Tracking - Jashan-randhawa/AI-FitnessTracker1 GitHub Wiki
π Health Analytics & Tracking
FitTrack AI provides a high-performance, real-time health dashboard that converts raw calorie numbers and activity records into actionable visual feedback.
β‘ 1. High-Performance $O(N)$ Daily Totals Engine (dailyTotals.ts)
To support fast load times as logs scale, FitTrack AI features a pure TypeScript daily aggregation engine:
- Single-Pass Aggregation (
buildDailyTotals): TraversesallFoodLogs,allActivityLogs, andallWaterLogsonce in linear $O(N)$ time, producing aMap<string, DayTotals>keyed by date string. - Precomputed Daily Metrics: Each date entry caches total calories, protein, carbs, fat, meal counts, burned calories (normalizing
calories ?? caloriesBurned ?? 0), active minutes, water intake, and active logging flags (hasFood,hasActivity). - Linear Streak Calculation (
calcStreakFromMap): Walks backwards day-by-day up to 365 days from today (or yesterday if today has no logs yet) in $O(D)$ time without re-scanning arrays or repeating string parses. - Lookup-Based Weekly Trends: 7-day chart windows are populated with instantaneous map lookups (
daily.get(date)), eliminating nested quadratic array scans.
π 2. Live Midnight Rollover (useToday Hook)
A common challenge in single-page health applications is keeping metrics accurate when a browser tab remains open across local midnight:
- Self-Arming Midnight Timer: Computes milliseconds until the next local midnight (
24:00:00) and arms a precisesetTimeout. Upon triggering, state updates to the newtoDateString()and immediately rearms for the following night. - Visibility Detection (
visibilitychange): Laptops in sleep mode or suspended background browser tabs can cause timers to drift or pause. The hook listens tovisibilitychangeand verifies whether the current date has advanced every time the user brings the tab back to focus. - Component Synchronization: The dynamic
todayvalue propagates to today's summary cards, meal filters, water intake tracker, streak calculators, and weekly chart windows without requiring a manual page refresh.
π― 3. Dynamic Goal Rings & Balance Meters
The top of the dashboard showcases three interactive SVG goal rings that scale smoothly across mobile viewports and wide desktop displays:
- Calories In (Emerald Ring): Tracks calories consumed against your daily caloric target.
- Calories Out (Orange Ring): Tracks active calories burned from logged workouts and cardio.
- Active Minutes (Blue Ring): Tracks physical activity duration against your daily goal (e.g. 45 mins).
$$\text{Net Calories} = \text{Calories Consumed} - \text{Calories Burned}$$
π 4. Weekly Insights Strip & Goal Reference Lines
Above the weekly trends chart, the dashboard provides a 4-tile summary strip computed across the last 7 days of the daily totals map:
- Average Calories In / Logged Day: Averages intake only across days with logged meals so empty days do not drag down the average.
- Average Calories Burned / Logged Day: Active energy expenditure per workout day.
- Days on Target (
x/7): Tracks compliance (days where calories in $\le$ limit with at least 1 meal logged). - Average Protein / Logged Day: Daily protein intake average for muscle maintenance.
- Week-over-Week Trends (β²/βΌ %): Compares the current 7-day window against the prior 7 days. Guarded with a $\ge 3$ logged days condition to prevent volatile or divide-by-zero percentages.
- Recharts Reference Lines:
- Calorie Tab: Renders dashed reference lines at
calorieLimitandcalorieBurnGoal. - Macro Tabs: Renders target reference lines at
dailyproteingoal,dailycarbsgoal, anddailyfatgoal. - Dynamic Rose Exceed Alert: Bars exceeding the daily calorie limit are highlighted in rose (
#f43f5e) via dynamic RechartsCellrendering.
- Calorie Tab: Renders dashed reference lines at
π₯© 5. Full-Stack Macro & Hydration Target Customization
Users can define exact targets in their profile or rely on automatic derivation:
- Custom Goals:
dailyproteingoal(g)dailycarbsgoal(g)dailyfatgoal(g)dailywatergoal(ml)
- Intelligent Fallback (
deriveGoals): When left unset, targets are derived automatically fromdailycaloriesintake:- Protein: 30% of total calories (4 kcal/g)
- Carbohydrates: 40% of total calories (4 kcal/g)
- Fats: 30% of total calories (9 kcal/g)
- Water: 2500 ml daily default
- Visual Progress Bars: Dashboard macro cards display real-time progress bars with
"x / goal g"format and percentage fills.
π 6. Gamified Achievements & Next-Badge Progress
- Activity Streak Engine: Tracks consecutive logging milestones and triggers celebratory full-screen Framer Motion confetti animations.
- Next-Badge Progress Card: Highlights the closest unearned milestone badge (e.g. "Week Warrior: 5/7 days") with an active progress bar and target indicator.
- Dynamic Greeting: Time-aware greeting adapted to local hours ("Good morning", "Good afternoon", "Good evening, {username}").
π
7. Interactive Calendar Heatmap (CalendarHeatmap)
Embedded in both Food Log and Activity Log:
- 90-Day Visual Window: Displays the past 12β13 weeks organized by day of the week (MonβSun).
- 4-Level Intensity Scale:
Level 0(Empty): No activity or food logged for the day.Level 1(Light): 1β499 kcal (Food) / 1β199 kcal (Activity).Level 2(Medium): 500β1,199 kcal (Food) / 200β399 kcal (Activity).Level 3(High): 1,200β1,999 kcal (Food) / 400β699 kcal (Activity).Level 4(Maximum): $\ge 2,000$ kcal (Food) / $\ge 700$ kcal (Activity).
- Streak Tracking: Displays current and maximum continuous streaks.
- Interactive Day Selection: Clicking any square filters the active log table directly to that selected date.
π§ 8. Interactive Hydration Tracker
- Visual Bottle Fill: Dynamic SVG hydration graphic that fills with water as you log intake.
- Quick-Add Presets:
+150ml,+250ml,+350ml,+500ml. - Custom Volume & Target: Log custom amounts in milliliters against your personalized
dailywatergoal.
βοΈ 9. Automated BMI & Data Exports
- Instant Calculation: $$\text{BMI} = \frac{\text{Weight (kg)}}{[\text{Height (m)}]^2}$$
- Data Exports (PDF, CSV & PNG):
- Formatted PDF Report: Multi-page report with stats summary, profile metrics, food logs, and activity records via jsPDF and AutoTable.
- Raw CSV Spreadsheets: Comma-separated history with timestamps and nutritional breakdown.
- Progress Card: Canvas-rendered progress card for social sharing via html2canvas.