From 8c51905b1f1a7c5baf37639b2af8d0bcccc3f600 Mon Sep 17 00:00:00 2001 From: Timothy Oluwatobi Ojebiyi Date: Wed, 4 Nov 2026 22:33:28 +0000 Subject: [PATCH 1/8] Add a light theme MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Colors now answers from the current palette (dark or a new light one tuned for contrast on white), so screens pick up the theme as they render. Styles that were computed once at load (sheet inputs, profile cards, buttons, settings rows, trend tabs, the scanner) are read at render instead. - Settings β†’ Account β†’ Appearance: System (follows the phone, live), Light or Dark, saved on the device. Changing it redraws the app and returns to the same screen. The status bar and screen backgrounds follow, and app.json now reports the phone's setting. --- apps/mobile/app.json | 2 +- apps/mobile/app/(tabs)/profile.tsx | 18 +++--- apps/mobile/app/_layout.tsx | 41 +++++++++++-- apps/mobile/app/barcode-scanner.tsx | 4 +- apps/mobile/app/profile/[id].tsx | 17 +++--- apps/mobile/app/settings/account.tsx | 15 +++++ apps/mobile/components/food/EditFoodSheet.tsx | 9 +-- apps/mobile/components/food/LogFoodSheet.tsx | 9 +-- .../components/plan/EditPlanDaySheet.tsx | 13 +++-- apps/mobile/components/stats/TrendsCard.tsx | 12 ++-- apps/mobile/components/ui/Button.tsx | 13 ++--- apps/mobile/constants/colors.ts | 58 ++++++++++++++++++- apps/mobile/stores/themeStore.ts | 30 ++++++++++ 13 files changed, 189 insertions(+), 52 deletions(-) create mode 100644 apps/mobile/stores/themeStore.ts diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 55b4126..bd7ef4d 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -6,7 +6,7 @@ "scheme": "grit", "orientation": "portrait", "icon": "./assets/icon.png", - "userInterfaceStyle": "dark", + "userInterfaceStyle": "automatic", "splash": { "image": "./assets/splash-icon.png", "resizeMode": "contain", diff --git a/apps/mobile/app/(tabs)/profile.tsx b/apps/mobile/app/(tabs)/profile.tsx index 2cf179a..30688b0 100644 --- a/apps/mobile/app/(tabs)/profile.tsx +++ b/apps/mobile/app/(tabs)/profile.tsx @@ -138,14 +138,14 @@ function EditSheet({ user, onClose }: { user: BackendUser; onClose: () => void } } const SETTINGS_ROWS = [ - { icon: '🎯', color: Colors.orange, label: 'Goals & Targets', sub: 'Calories, macros and weight goal', href: '/settings/goals' as const }, - { icon: 'πŸ‹οΈ', color: Colors.teal, label: 'Workout Plan', sub: 'Your weekly plan from the coach', href: '/plan' as const }, - { icon: 'πŸ‘₯', color: Colors.orange, label: 'Friends', sub: 'Find people, requests and followers', href: '/friends' as const }, - { icon: 'πŸ”’', color: Colors.blue, label: 'Privacy', sub: 'Private account and blocked people', href: '/settings/privacy' as const }, - { icon: 'πŸ””', color: Colors.blue, label: 'Notifications', sub: 'Reminders and alerts', href: '/settings/notifications' as const }, - { icon: 'πŸ‘€', color: Colors.muted, label: 'Account', sub: 'Units, password, delete account', href: '/settings/account' as const }, - { icon: 'πŸ“Š', color: Colors.teal, label: 'My Progress', sub: 'Weekly stats', href: '/(tabs)/activity' as const }, - { icon: 'πŸ’¬', color: Colors.muted, label: 'Help & Feedback', sub: 'Email support', href: null }, + { icon: '🎯', color: 'orange' as const, label: 'Goals & Targets', sub: 'Calories, macros and weight goal', href: '/settings/goals' as const }, + { icon: 'πŸ‹οΈ', color: 'teal' as const, label: 'Workout Plan', sub: 'Your weekly plan from the coach', href: '/plan' as const }, + { icon: 'πŸ‘₯', color: 'orange' as const, label: 'Friends', sub: 'Find people, requests and followers', href: '/friends' as const }, + { icon: 'πŸ”’', color: 'blue' as const, label: 'Privacy', sub: 'Private account and blocked people', href: '/settings/privacy' as const }, + { icon: 'πŸ””', color: 'blue' as const, label: 'Notifications', sub: 'Reminders and alerts', href: '/settings/notifications' as const }, + { icon: 'πŸ‘€', color: 'muted' as const, label: 'Account', sub: 'Appearance, units, password, delete account', href: '/settings/account' as const }, + { icon: 'πŸ“Š', color: 'teal' as const, label: 'My Progress', sub: 'Weekly stats', href: '/(tabs)/activity' as const }, + { icon: 'πŸ’¬', color: 'muted' as const, label: 'Help & Feedback', sub: 'Email support', href: null }, ]; export default function ProfileScreen() { @@ -354,7 +354,7 @@ export default function ProfileScreen() { gap: 14, })} > - + {row.icon} diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index b025e5b..19c87db 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -1,5 +1,6 @@ import '../global.css'; -import React, { useEffect } from 'react'; +import React, { useEffect, useRef } from 'react'; +import { useColorScheme } from 'react-native'; import { Stack, SplashScreen, router, useSegments, usePathname } from 'expo-router'; import { QueryClientProvider } from '@tanstack/react-query'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; @@ -19,6 +20,8 @@ import { queryClient } from '@/lib/queryClient'; import { useAuthStore } from '@/stores/authStore'; import { usePushNotifications } from '@/hooks/usePushNotifications'; import { Toast } from '@/components/ui/Toast'; +import { Colors, applyColorScheme } from '@/constants/colors'; +import { useThemeStore } from '@/stores/themeStore'; import { OfflineBanner } from '@/components/ui/OfflineBanner'; import { CrashScreen } from '@/components/ui/CrashScreen'; import { installGlobalCrashHandler, setCrashScreen } from '@/lib/crashReporter'; @@ -38,6 +41,36 @@ export default function RootLayout() { // Register for push only once signed in; the backend rejects anonymous calls usePushNotifications(!!session); + // Theme: the saved choice, or the phone's setting. Colors answers from the + // current palette, so set it before anything below renders. + const systemScheme = useColorScheme(); + const { preference, loaded: themeLoaded, load: loadTheme } = useThemeStore(); + useEffect(() => { loadTheme(); }, [loadTheme]); + const scheme = preference === 'system' ? (systemScheme === 'light' ? 'light' : 'dark') : preference; + applyColorScheme(scheme); + + // Screens are memoised by the navigator, so a theme change redraws them by + // remounting the stack (keyed on the scheme), then reopens the screen the + // user was on + const schemeRef = useRef(scheme); + const pathRef = useRef(pathname); + const restoreTo = useRef(null); + if (schemeRef.current !== scheme) { + restoreTo.current = pathRef.current; + schemeRef.current = scheme; + } else if (!restoreTo.current) { + pathRef.current = pathname; + } + useEffect(() => { + const path = restoreTo.current; + if (!path) return; + const timer = setTimeout(() => { + restoreTo.current = null; + if (path !== '/') router.replace(path as never); + }, 0); + return () => clearTimeout(timer); + }, [scheme]); + const [fontsLoaded, fontError] = useFonts({ 'DMSans-Regular': DMSans_400Regular, 'DMSans-Medium': DMSans_500Medium, @@ -99,15 +132,15 @@ export default function RootLayout() { router.replace(onboardingComplete ? '/(auth)/login' : '/onboarding'); }, [ready, session, publicRoute, onboardingComplete]); - if (isLoading || onboardingLoading || !fontsReady) { + if (isLoading || onboardingLoading || !fontsReady || !themeLoaded) { return null; } return ( - - + + diff --git a/apps/mobile/app/barcode-scanner.tsx b/apps/mobile/app/barcode-scanner.tsx index bb4f842..8d41b4f 100644 --- a/apps/mobile/app/barcode-scanner.tsx +++ b/apps/mobile/app/barcode-scanner.tsx @@ -9,6 +9,7 @@ import { LogFoodSheet } from '@/components/food/LogFoodSheet'; import { Colors } from '@/constants/colors'; export default function BarcodeScannerScreen() { + const styles = makeStyles(); const [permission, requestPermission] = useCameraPermissions(); const [scannedCode, setScannedCode] = useState(null); const [showSheet, setShowSheet] = useState(false); @@ -154,7 +155,8 @@ const CORNER_SIZE = 24; const CORNER_THICKNESS = 3; const CORNER_COLOR = Colors.orange; -const styles = StyleSheet.create({ +// Built during render, so it follows the current theme +const makeStyles = () => StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.dark }, overlay: { flex: 1, diff --git a/apps/mobile/app/profile/[id].tsx b/apps/mobile/app/profile/[id].tsx index efa7dc2..17479bc 100644 --- a/apps/mobile/app/profile/[id].tsx +++ b/apps/mobile/app/profile/[id].tsx @@ -24,13 +24,14 @@ const GOAL_LABELS: Record = { just_track: 'Just tracking', }; -const card = { +/** Read during render, so it follows the current theme */ +const card = () => ({ backgroundColor: Colors.surface, borderRadius: 20, padding: 16, borderWidth: 1, borderColor: Colors.border, -} as const; +} as const); export default function ProfileScreen() { const { id } = useLocalSearchParams<{ id: string }>(); @@ -104,7 +105,7 @@ export default function ProfileScreen() { {menuOpen && ( - + {rel?.followsYou === 'accepted' && ( Remove follower @@ -137,7 +138,7 @@ export default function ProfileScreen() { {rel?.blocked ? ( - + You blocked {name} Unblock them to see their profile again. You'll need to follow each other again. @@ -154,7 +155,7 @@ export default function ProfileScreen() { ) : ( <> {/* Counts */} - + {([ { label: 'Followers', value: profile._count.followers, which: 'followers' }, { label: 'Following', value: profile._count.following, which: 'following' }, @@ -175,7 +176,7 @@ export default function ProfileScreen() { {/* They asked to follow you */} {rel?.followsYou === 'pending' && ( - + {name} wants to follow you. accept(profile.id)} disabled={accepting} accessibilityRole="button" style={{ flex: 1, backgroundColor: Colors.orange, borderRadius: 999, paddingVertical: 10, alignItems: 'center' }}> @@ -199,7 +200,7 @@ export default function ProfileScreen() { )} {!profile.canView ? ( - + πŸ”’ This account is private @@ -211,7 +212,7 @@ export default function ProfileScreen() { ) : ( <> {profile.week && ( - + {[ { label: 'Active min', value: profile.week.activeMinutes }, { label: 'Workouts', value: profile.week.workouts }, diff --git a/apps/mobile/app/settings/account.tsx b/apps/mobile/app/settings/account.tsx index d66e156..1478d9e 100644 --- a/apps/mobile/app/settings/account.tsx +++ b/apps/mobile/app/settings/account.tsx @@ -8,6 +8,7 @@ import { api } from '@/lib/api'; import { removeAvatarFile } from '@/lib/avatar'; import { supabase } from '@/lib/supabase'; import { signOut } from '@/lib/session'; +import { useThemeStore } from '@/stores/themeStore'; import { confirmAction, notify } from '@/lib/confirm'; import { sendPasswordReset } from '@/lib/passwordReset'; import { useAuthStore } from '@/stores/authStore'; @@ -16,6 +17,8 @@ import { ChipGroup, FieldLabel, NavRow, ScreenHeader, Section } from '@/componen export default function AccountScreen() { const { data: me } = useMe(); + const themePreference = useThemeStore((s) => s.preference); + const setThemePreference = useThemeStore((s) => s.setPreference); const { mutate: save } = useUpdateMe(); const email = useAuthStore((s) => s.user?.email); const [busy, setBusy] = useState(false); @@ -66,6 +69,18 @@ export default function AccountScreen() { {email ?? 'β€”'} +
+ +
+ {me && (
diff --git a/apps/mobile/components/food/EditFoodSheet.tsx b/apps/mobile/components/food/EditFoodSheet.tsx index 4ae5c93..a3108f0 100644 --- a/apps/mobile/components/food/EditFoodSheet.tsx +++ b/apps/mobile/components/food/EditFoodSheet.tsx @@ -11,7 +11,8 @@ import { Colors } from '@/constants/colors'; const MEALS = ['breakfast', 'lunch', 'dinner', 'snack'] as const; -const fieldStyle = { +/** Read during render, so it follows the current theme */ +const fieldStyle = () => ({ backgroundColor: Colors.surface2, borderRadius: 14, padding: 12, @@ -20,7 +21,7 @@ const fieldStyle = { fontSize: 16, borderWidth: 1.5, borderColor: Colors.border, -} as const; +} as const); const round1 = (n: number) => String(Math.round(n * 10) / 10); const parse = (s: string) => (s.trim() === '' ? NaN : Number(s)); @@ -72,7 +73,7 @@ export function EditFoodSheet({ log, onClose }: { log: FoodLog; onClose: () => v value={values[key]} onChangeText={(t) => setValues((v) => ({ ...v, [key]: t.replace(/[^0-9.]/g, '') }))} keyboardType="decimal-pad" - style={fieldStyle} + style={fieldStyle()} accessibilityLabel={label} /> @@ -96,7 +97,7 @@ export function EditFoodSheet({ log, onClose }: { log: FoodLog; onClose: () => v onChangeText={setName} placeholder="Food name" placeholderTextColor={Colors.muted} - style={{ ...fieldStyle, fontFamily: 'DMSans-Regular' }} + style={{ ...fieldStyle(), fontFamily: 'DMSans-Regular' }} accessibilityLabel="Food name" /> diff --git a/apps/mobile/components/food/LogFoodSheet.tsx b/apps/mobile/components/food/LogFoodSheet.tsx index f19541b..3af75e3 100644 --- a/apps/mobile/components/food/LogFoodSheet.tsx +++ b/apps/mobile/components/food/LogFoodSheet.tsx @@ -17,7 +17,8 @@ import { loggedAtFor } from '@/lib/date'; const MEAL_TYPES = ['breakfast', 'lunch', 'dinner', 'snack'] as const; -const fieldStyle = { +/** Read during render, so it follows the current theme */ +const fieldStyle = () => ({ backgroundColor: Colors.surface2, borderRadius: 16, padding: 12, @@ -26,7 +27,7 @@ const fieldStyle = { fontSize: 16, borderWidth: 1.5, borderColor: Colors.border, -} as const; +} as const); type MealType = typeof MEAL_TYPES[number]; interface LogFoodSheetProps { @@ -136,7 +137,7 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP {isManual ? ( setManual((m) => ({ ...m, [key]: v }))} keyboardType="decimal-pad" diff --git a/apps/mobile/components/plan/EditPlanDaySheet.tsx b/apps/mobile/components/plan/EditPlanDaySheet.tsx index 05beabf..e84d18d 100644 --- a/apps/mobile/components/plan/EditPlanDaySheet.tsx +++ b/apps/mobile/components/plan/EditPlanDaySheet.tsx @@ -11,7 +11,8 @@ import { Colors } from '@/constants/colors'; const MAX_EXERCISES = 12; -const inputStyle = { +/** Read during render, so it follows the current theme */ +const inputStyle = () => ({ backgroundColor: Colors.surface2, borderRadius: 12, borderWidth: 1, @@ -21,7 +22,7 @@ const inputStyle = { color: Colors.text, fontFamily: 'DMSans-Regular', fontSize: 14, -} as const; +} as const); /** Edit one day of the plan by hand: rest or train, title, type, length and exercises. */ export function EditPlanDaySheet({ day, onClose }: { day: PlanDay; onClose: () => void }) { @@ -81,7 +82,7 @@ export function EditPlanDaySheet({ day, onClose }: { day: PlanDay; onClose: () = - + {!rest && ( <> @@ -101,15 +102,15 @@ export function EditPlanDaySheet({ day, onClose }: { day: PlanDay; onClose: () = Minutes - setDuration(t.replace(/[^0-9]/g, ''))} keyboardType="number-pad" maxLength={3} style={{ ...inputStyle, width: 80, fontFamily: 'JetBrainsMono-Regular' }} accessibilityLabel="Minutes" /> + setDuration(t.replace(/[^0-9]/g, ''))} keyboardType="number-pad" maxLength={3} style={{ ...inputStyle(), width: 80, fontFamily: 'JetBrainsMono-Regular' }} accessibilityLabel="Minutes" /> Exercises {exercises.map((e, i) => ( - setExercise(i, { name: t })} placeholder="Exercise" placeholderTextColor={Colors.muted} maxLength={80} style={{ ...inputStyle, flex: 2 }} accessibilityLabel={`Exercise ${i + 1}`} /> - setExercise(i, { detail: t })} placeholder="3 Γ— 12" placeholderTextColor={Colors.muted} maxLength={60} style={{ ...inputStyle, flex: 1 }} accessibilityLabel={`Sets for exercise ${i + 1}`} /> + setExercise(i, { name: t })} placeholder="Exercise" placeholderTextColor={Colors.muted} maxLength={80} style={{ ...inputStyle(), flex: 2 }} accessibilityLabel={`Exercise ${i + 1}`} /> + setExercise(i, { detail: t })} placeholder="3 Γ— 12" placeholderTextColor={Colors.muted} maxLength={60} style={{ ...inputStyle(), flex: 1 }} accessibilityLabel={`Sets for exercise ${i + 1}`} /> setExercises((list) => list.filter((_, j) => j !== i))} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Remove exercise ${i + 1}`}> βœ• diff --git a/apps/mobile/components/stats/TrendsCard.tsx b/apps/mobile/components/stats/TrendsCard.tsx index adc00a9..bf250c1 100644 --- a/apps/mobile/components/stats/TrendsCard.tsx +++ b/apps/mobile/components/stats/TrendsCard.tsx @@ -14,11 +14,11 @@ const RANGES: { value: TrendRange; label: string }[] = [ { value: 30, label: '30D' }, { value: 90, label: '3M' }, ]; -const METRICS: { value: Metric; label: string; color: string }[] = [ - { value: 'calories', label: 'Calories', color: Colors.orange }, - { value: 'protein', label: 'Protein', color: Colors.blue }, - { value: 'activity', label: 'Activity', color: Colors.teal }, - { value: 'weight', label: 'Weight', color: Colors.orange }, +const METRICS: { value: Metric; label: string; color: 'orange' | 'blue' | 'teal' }[] = [ + { value: 'calories', label: 'Calories', color: 'orange' }, + { value: 'protein', label: 'Protein', color: 'blue' }, + { value: 'activity', label: 'Activity', color: 'teal' }, + { value: 'weight', label: 'Weight', color: 'orange' }, ]; const CHART_H = 120; @@ -142,7 +142,7 @@ export function TrendsCard({ unit, onLogWeight }: { unit: WeightUnit; onLogWeigh const { data, isLoading, isError, refetch } = useTrends(range); const weight = useWeightHistory(range === 90 ? 90 : 30); const { mutate: deleteWeight } = useDeleteWeight(); - const color = METRICS.find((m) => m.value === metric)!.color; + const color = Colors[METRICS.find((m) => m.value === metric)!.color]; const weekly = range === 90; const view = useMemo(() => { diff --git a/apps/mobile/components/ui/Button.tsx b/apps/mobile/components/ui/Button.tsx index cc8611f..a5454c0 100644 --- a/apps/mobile/components/ui/Button.tsx +++ b/apps/mobile/components/ui/Button.tsx @@ -72,15 +72,14 @@ const baseText = { letterSpacing: 0.2, }; +// Getters, so each read uses the current theme's colours const styles = { - primaryBg: { backgroundColor: Colors.orange }, - secondaryBg: { - backgroundColor: 'transparent', - borderWidth: 1.5, - borderColor: Colors.orange, + get primaryBg() { return { backgroundColor: Colors.orange }; }, + get secondaryBg() { + return { backgroundColor: 'transparent', borderWidth: 1.5, borderColor: Colors.orange }; }, ghostBg: { backgroundColor: 'transparent' }, primaryText: { color: '#fff' }, - secondaryText: { color: Colors.orange }, - ghostText: { color: Colors.muted }, + get secondaryText() { return { color: Colors.orange }; }, + get ghostText() { return { color: Colors.muted }; }, }; diff --git a/apps/mobile/constants/colors.ts b/apps/mobile/constants/colors.ts index 2307422..01e4dc4 100644 --- a/apps/mobile/constants/colors.ts +++ b/apps/mobile/constants/colors.ts @@ -1,5 +1,15 @@ -export const Colors = { +/** + * The app's colours, for a dark and a light theme. + * + * Screens read `Colors.x` while rendering, so `Colors` always answers from + * the current palette. When the theme changes, the root layout redraws the + * screens (see components/ThemeRoot.tsx). Don't copy a colour into a value + * computed once at module load; read it during render instead. + */ + +const DARK = { orange: '#FF5C2B', + /** Page background */ dark: '#0F0F0F', surface: '#1A1A1C', surface2: '#242428', @@ -11,4 +21,48 @@ export const Colors = { blue: '#4B9FFF', border: '#2B2B30', error: '#FF453A', -} as const; +}; + +export type Palette = typeof DARK; +export type ColorScheme = 'light' | 'dark'; + +// Same roles, tuned for a light background: deeper accents keep text and +// icons readable (muted text is 5:1 on white) +const LIGHT: Palette = { + orange: '#EC5020', + dark: '#F6F4F1', + surface: '#FFFFFF', + surface2: '#F1EEEA', + surface3: '#E5E1DC', + text: '#1A1714', + muted: '#68625D', + teal: '#00957A', + success: '#00957A', + blue: '#2C75D6', + border: '#E2DDD7', + error: '#D93025', +}; + +let current: Palette = DARK; +let currentScheme: ColorScheme = 'dark'; + +export const Colors: Palette = new Proxy({} as Palette, { + get: (_target, key: string) => current[key as keyof Palette], + ownKeys: () => Reflect.ownKeys(current), + getOwnPropertyDescriptor: (_target, key) => ({ + enumerable: true, + configurable: true, + value: current[key as keyof Palette], + }), +}); + +export function applyColorScheme(scheme: ColorScheme) { + current = scheme === 'light' ? LIGHT : DARK; + currentScheme = scheme; +} + +export function colorScheme(): ColorScheme { + return currentScheme; +} + +export const PALETTES = { dark: DARK, light: LIGHT } as const; diff --git a/apps/mobile/stores/themeStore.ts b/apps/mobile/stores/themeStore.ts new file mode 100644 index 0000000..acc9668 --- /dev/null +++ b/apps/mobile/stores/themeStore.ts @@ -0,0 +1,30 @@ +import { create } from 'zustand'; +import { storage } from '@/lib/storage'; + +export type ThemePreference = 'system' | 'light' | 'dark'; + +const KEY = 'grit_theme'; + +interface ThemeState { + preference: ThemePreference; + loaded: boolean; + load: () => Promise; + setPreference: (p: ThemePreference) => void; +} + +/** Light, dark, or follow the phone. Saved on the device. */ +export const useThemeStore = create((set) => ({ + preference: 'system', + loaded: false, + load: async () => { + const saved = await storage.getItem(KEY).catch(() => null); + set({ + preference: saved === 'light' || saved === 'dark' || saved === 'system' ? saved : 'system', + loaded: true, + }); + }, + setPreference: (preference) => { + set({ preference }); + storage.setItem(KEY, preference).catch(() => {}); + }, +})); From 4c44989729aa8961f8a6fa9cd8ef6c3ff7164cdc Mon Sep 17 00:00:00 2001 From: Timothy Oluwatobi Ojebiyi Date: Wed, 4 Nov 2026 22:33:48 +0000 Subject: [PATCH 2/8] Add Phase 4 market research Competitive landscape, category gaps and ranked moat candidates, with sources. It sets the Phase 4 priorities: AI meal logging grounded in a food database and the user's history, adaptive calorie targets, and a coach with memory that acts across nutrition, training, habits and friends. --- docs/MARKET_RESEARCH.md | 126 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 docs/MARKET_RESEARCH.md diff --git a/docs/MARKET_RESEARCH.md b/docs/MARKET_RESEARCH.md new file mode 100644 index 0000000..cc1fde5 --- /dev/null +++ b/docs/MARKET_RESEARCH.md @@ -0,0 +1,126 @@ + + +# GRIT Competitive Research: Phase 4 Moat Features (Nov 2026) + +**Method note.** Most web-page fetches were blocked in this session (macrofactor.com, aol.com and others would not resolve), so this report rests on search-result extracts. Many 2026 "reviews" come from competitor SEO blogs (Nutrola, NutriScan, SensAI, GAYA). I used them only for user-sentiment themes, and prices marked "~" are unverified. Press releases and trade press (TechCrunch, BusinessWire, GlobeNewswire, 9to5Mac, Healio) carry the firm claims. + +## 1. Landscape + +| App | Positioning | Standout features (2025–26 news in bold) | Top complaints | Price (2026) | +|---|---|---|---|---| +| **MyFitnessPal** | Mass-market tracker, biggest database | **Acquired Cal AI (announced Mar 2026)**; **ChatGPT Health app (Jan 2026)**; **AI Coach, Premium only (Jun 2026)**; **free GLP-1 support (Apr 2026)**; Meal Planner (Intent acquisition) in Premium+ | Barcode scan paywalled since 2022; ads; crowdsourced data errors; **Apr 2026 "Today" redesign backlash, no way back to old Diary, reported data-loss bugs** | Free; Premium $79.99/yr ($19.99/mo); Premium+ $99.99/yr | +| **Lose It!** | Simple weight-loss counter | Snap It (photo) + Say It (voice) logging, trial for free users; GLP-1 tracking listed 2026 (unverified) | Barcode scan reportedly moving to Premium for new users; ads; duplicate entries | ~$39.99/yr | +| **Cronometer** | Micronutrient accuracy, lab-verified database | **Photo Logging, Gold-only (beta Feb 2026)**, matches to its verified database | Dated UI; photo logging immature | Gold ~$50–60/yr (sources conflict) | +| **MacroFactor** | Evidence-based adaptive macro coach | Adaptive expenditure algorithm (V3 + **Expenditure Modifiers, Oct 2025**); AI Describe (text/voice) + photo; **separate Workouts app (Jan 2026)**, **Plate-Stack AI (Jul 2026)** | No free tier; algorithm slow to converge and noisy with menstrual-cycle water swings; minimal social; two apps, two subscriptions | $71.99/yr; Workouts $71.99/yr; bundle ~$89.99 | +| **Cal AI** (+ photo-first clones) | Snap-a-photo, Gen-Z virality | Photo calorie estimate; 15M+ downloads, $30–40M/yr revenue | Accuracy (see gap #1); **pulled from App Store Apr 2026 over deceptive paywall, later restored**; billing-trial complaints | ~$20–30/yr, dynamic | +| **Yazio** | EU-centric tracker + fasting | Fasting, recipes, photo logging in PRO (claims conflict) | Paywall creep | ~$45–48/yr | +| **Lifesum** | Lifestyle/diet plans | Multimodal tracker (photo/voice/text, Feb 2025) | Misidentified foods (cashews logged as shrimp), barcode calories doubled | Unclear (~$99.99/yr cited) | +| **Noom** | Psychology program, now GLP-1 telehealth | Noom Med GLP-1Rx + **Microdose GLP-1 (2026)** | Cost; upsell-heavy | GLP-1Rx from $129, then $279/mo; Microdose $79 intro, then $199/mo | +| **Carbon Diet Coach** | Layne Norton's adaptive macros | Weekly check-in with algorithmic macro adjustment | No free tier; nutrition only; thin logging (barcode reportedly missing) | ~$80–120/yr (conflicting) | +| **Strava** | Endurance social network | Social graph, clubs, segments; Athlete Intelligence AI summaries; **bought Runna (Apr 2026), joint bundle** | Paywalled analytics; AI summaries seen as shallow; no nutrition | $79.99/yr; +Runna $149.99/yr | +| **Fitbod** | Algorithmic strength programming | Auto progressive overload | **2026 price hike**; rotates exercises too often to progress on specific lifts | $95.99/yr new subs (legacy $79.99) | +| **Hevy** | Free social lift logger | Generous free tier, feed, PRs, strength-level comparisons | No programming or coaching | Pro ~$23.99/yr | +| **Ladder / Future** | Human-coached training | Ladder: coach-led group programs. Future: 1:1 human coach. **Future reportedly scrapped its AI coach (Jun 2026)** to focus on humans | Price; Ladder is iOS-only and not individualised | Ladder ~$150–180/yr; Future $149–199/mo | +| **WHOOP / Oura** | Wearable recovery + AI advisor | **WHOOP "My Memory" (7 editable memory categories) + Proactive Check-Ins (May 2026)**; Oura Advisor with user-controlled memory (2025) | Nutrition logging weak or absent; hardware-locked | Subscription bundled with hardware (not verified) | +| **Streaks / Habitica** | Habit trackers | Streaks: polished iOS app, Health auto-complete. Habitica: gamified, social | Streaks has a 24-habit cap and no social; Habitica feels overbuilt | Streaks $5.99 one-time; Habitica free + extras | + +## 2. Category gaps (ranked) + +1. **AI logging is fast but inaccurate, and every app hides it behind a paywall.** In a NUTRITION 2026 study of 102 controlled meals (preliminary), photo features underestimated energy by about 33%: Cal AI by 345 kcal, Lose It! by 333 and MyFitnessPal by 327, with fat undercounted by about 30 g per meal. Accuracy was worse for keto meals. The researchers suggest combining photo AI with traditional database logging. MFP's Meal Scan and Cronometer's photo logging both need a paid tier. +2. **Basic features keep moving behind paywalls, plus ads.** MFP's barcode scan has been Premium-only since 2022, Lose It! is reportedly paywalling barcode scanning for new users, and one market analysis links Lose It!'s falling sentiment to "aggressive paywalling of legacy features". Cal AI was removed from the App Store over its paywall design. +3. **Bad database data.** In an analysis of 50,000 reviews (by a competitor), inaccurate data made up 15.7% of complaints overall and 24.1% among long-term users. MFP's crowdsourced entries draw the most criticism, and Lifesum's barcode scans reportedly double or triple calories. +4. **Targets don't adapt.** On MFP, users set and fix their own targets. MacroFactor's expenditure algorithm is "the whole USP" according to its subreddit, but it costs $72/yr with no free tier, and Carbon has none either. +5. **Logging falls off after a few weeks, and nothing holds people to it.** In two 6-month trials, fewer than half of participants were still self-monitoring by week 10. Supportive-accountability scores correlate with adherence (JMIR 2020). Nutrition apps have weak social features, and Strava and Hevy have strong social features but no nutrition. +6. **AI coaches are siloed and forgetful.** MFP's AI Coach (Jun 2026) covers nutrition only and is Premium-only. Strava's AI summaries cover training only. WHOOP and Oura only recently added memory, and they lack serious food data. Even coaches are wary: 54% worry about the accuracy of AI advice (FitBudd, a vendor survey). +7. **Nutrition and training live in separate apps.** MacroFactor needed a second app and a second subscription for workouts, Fitbod raised prices, and Hevy is free but has no coaching. +8. **Redesigns break habits.** MFP's April 2026 "Today" redesign reportedly drove version ratings from ~3.2 to ~1.5, with no way to revert. + +## 3. Recommended Phase 4 moat features (ranked) + +### 1. Multimodal "Say / Snap / Type" logging, grounded in a database and your history (BUILD FIRST) +- **What it is.** You type or say "2 eggs, toast with butter, flat white" or snap a photo. The LLM breaks the meal into items, grams and cooking method. Each item is then matched to Open Food Facts, USDA FoodData Central, or your own recent and favourite foods. Before saving, you see a confirm sheet with portion sliders. When something is ambiguous, the app asks one clarifying question, such as "cooked in oil?". Recipe-URL import uses the same pipeline. +- **Why it's a moat for GRIT.** On its own this is now table stakes, but personalised it compounds. Every correction ("my usual oats = 60 g") goes into a per-user food memory, so logging gets faster and more accurate the longer someone uses GRIT, which a new app can't match on day one. Offering it free would hit competitors where they paywall. +- **Evidence of demand.** Lose It! reports 3.5x faster logging and 2x more foods logged with AI (vendor data). MacroFactor, MFP, Cronometer, Lifesum and Yazio all shipped versions in 2025–26, and Cal AI built $30M+/yr of revenue on it. +- **Who does it, and how well.** Accuracy is poor across the board (about βˆ’33%). MacroFactor grounds AI Describe in its database, which is the right pattern. Cronometer's version is Gold-only and limited. +- **Build note.** Mobile: expo-camera / expo-image-picker, plus audio sent to Azure OpenAI transcription (or on-device speech). Backend: a NestJS `POST /food/parse` endpoint calls the vision-capable GPT with a strict JSON schema (structured outputs). The LLM estimates portions only; nutrients per gram always come from the database. Prisma models: `ParsedMeal`, `FoodAlias` (user-specific corrections). Reuse the coach's daily cap for cost control, add a "low confidence" flag, and log the photo-vs-confirmed difference to tune prompts. + +### 2. Adaptive TDEE with a weekly check-in (BUILD FIRST) +- **What it is.** Estimated expenditure = intake βˆ’ (change in weight-trend Γ— ~7,700 kcal/kg) / days. Start from the Mifflin estimate and blend toward the observed value as data comes in. Days with incomplete logs are excluded. A weekly check-in proposes a new calorie and macro target, and the coach explains why in one paragraph. +- **Why it's a moat for GRIT.** GRIT already has weigh-ins, intake, MET-based burn, earnback, rollover and a weekly check-in push, so most of the inputs exist. GRIT can do something MacroFactor can't: reconcile logged training with weight trend to auto-calibrate earnback, for example "your workouts burn ~70% of the MET estimate". The estimate improves with personal history, which gives the switching cost MacroFactor users cite. +- **Evidence of demand.** r/MacroFactor users call the expenditure algorithm "the whole USP" and value being told "how much to eat each week". Carbon charges ~$80–120/yr for little more than this. +- **Who does it, and how well.** MacroFactor does it well but behind $72/yr; Carbon is paid only; MFP and Lose It! use static targets. +- **Build note.** A nightly @nestjs/schedule job computes an EWMA weight trend and runs a simple Kalman/Bayesian update. Prisma: `ExpenditureEstimate(date, value, confidence)` and `TargetProposal(status)`. Require at least 14 days of data and about 80% logging completeness. Let the user accept, adjust or ignore each proposal. Add guardrails: a minimum calorie floor and a maximum weekly change. Optionally add cycle-aware smoothing (a known MacroFactor complaint). + +### 3. Coach with long-term memory that acts proactively, across nutrition, training, habits and social (BUILD FIRST) +- **What it is.** The coach keeps an editable memory ("What Coach knows about me": goals, injuries, schedule, food dislikes, events), as WHOOP's My Memory does. Event triggers fire proactive messages: two days without logging, protein short three days running, a weight plateau, a PR, a challenge about to be lost, a friend who has been quiet. Through tool calls (with user confirmation), the coach can change the workout plan, habits or targets. +- **Why it's a moat for GRIT.** No competitor holds all four data streams plus a social graph. MFP's coach sees food only, Strava's sees training only, WHOOP's sees recovery without real food data. Memory accumulates per user, so switching means starting over. +- **Evidence of demand.** WHOOP (May 2026) and Oura (2025) shipped memory and proactive check-ins, MFP shipped its AI Coach (Jun 2026), and MFP built a ChatGPT integration. On the other side, Future dropped its AI coach in favour of human coaches, a sign that generic AI coaches disappoint. +- **Build note.** Prisma model: `CoachMemory(category, text, source, confidence, expiresAt)`. Retrieve memories with pgvector on Supabase, or with a simple category filter at first. After each chat, the GPT extracts memory candidates through a tool call. A rules engine (cron) detects triggers, the GPT drafts the message, and it is delivered through the existing inbox and push. Register tools such as `updateWorkoutPlan`, `proposeTarget` and `addHabit`, and require user approval for each change. Add a privacy screen to view and delete memories. + +### 4. Squads: small accountability groups and partners +- **What it is.** Groups of 2–6 people with shared weekly commitments (log five days, hit protein, three workouts). Challenges can be built on habits and nutrition, not just steps and minutes. Partners can do a "check on a friend" one-tap nudge, and the coach writes a weekly squad recap. +- **Why it's a moat for GRIT.** This is a social-graph network effect: the more friends someone has on GRIT, the harder it is to leave. It reuses GRIT's existing friends, kudos, challenges and streak-at-risk push. MacroFactor and Cronometer have essentially no social features, and Strava and Hevy have no nutrition. +- **Evidence of demand.** Self-monitoring collapses by week 10, and supportive accountability correlates with adherence (JMIR 2020). NCT05180448 is testing data-sharing with groups and friends, but its results are unpublished, so this is unverified. +- **Build note.** Prisma: `Squad`, `SquadMember`, `SquadGoal`, `Nudge`. Generalise the challenge engine's metric source to habits and nutrition. Rate-limit nudges. This is mostly CRUD plus push, a low-risk build. + +### 5. GLP-1 mode +- **What it is.** Medication and dose-day log, side-effect journal, protein-first and lower-volume targets, hydration and fibre habits, and a strength-training emphasis to preserve muscle (GRIT's training data is an edge here). Also a "coming off the drug" maintenance plan. +- **Why it's a moat for GRIT.** It combines nutrition, training, habits and coach where competitors offer nutrition-only logging. The muscle-preservation and maintenance angles are underserved. +- **Evidence of demand.** 12% of US adults are currently taking a GLP-1 (KFF, Nov 2025). MFP made its GLP-1 support free (Apr 2026), MyNetDiary launched a companion (May 2026), and Noom built a telehealth business around the drugs. +- **Caveat.** This is quickly becoming table stakes and is not deeply defensible. Avoid dosing advice; it is a medical and regulatory risk. +- **Build note.** Add a med-log model, reuse habits for reminders, add a target preset, and give the coach prompt context and guardrails. + +### 6. Progressive-overload strength tracking linked to nutrition +- **What it is.** Set, rep and load logging, PRs and e1RM, auto-progression suggestions inside the coach's weekly plan. Training-day versus rest-day macros feed into feature #2. +- **Why it's a moat for GRIT.** It joins what MacroFactor sells as two apps and two subscriptions. Fitbod's price hike and exercise-rotation complaints leave an opening. +- **Caveat.** This is the largest build and Hevy is cheap and good, so treat it as later Phase 4. Sleep- and recovery-aware coaching should ride on the Health Connect / Apple Health work already in progress, as an input to #3 rather than a separate feature. +- **Build note.** Prisma models: `Exercise`, `WorkoutSet`. Use an exercise library seed (e.g. the open-source free-exercise-db). Drive progression with rules such as double progression or RPE, and let the coach explain them. + +**Deprioritised.** Meal planning: MFP Premium+ owns it and LLM meal plans are generic, so it's better offered as a coach action. Restaurant logging: data licensing is hard, so fold it into #1 ("Chipotle bowl, chicken, rice…"). + +**Build first: #1, #2, #3.** Free AI logging removes the category's biggest pain and paywall. Adaptive targets create personal-data lock-in. A cross-domain memory coach is the one thing no competitor can copy without owning all four data types. #4 is cheap and can ship alongside. + +**Could not verify:** Lose It!, Cronometer, Lifesum, Carbon and Ladder prices; whether Yazio has photo logging; WHOOP/Oura subscription prices; the MacroFactor bundle price; Future cancelling its AI coach (one source); Lose It!'s GLP-1 feature. Treat Reddit sentiment as indicative: no 2026 r/MacroFactor threads were readable. + +## Sources +- https://techcrunch.com/2026/03/02/myfitnesspal-has-acquired-cal-ai-the-viral-calorie-app-built-by-teens +- https://thenextweb.com/news/myfitnesspal-acquires-cal-ai-the-viral-calorie-tracking-app-built-by-teens +- https://www.globenewswire.com/news-release/2026/04/28/3282728/0/en/MyFitnessPal-Launches-Comprehensive-GLP-1-Support-Helping-Users-Stay-Consistent-and-Build-Habits-Alongside-Medication-to-Maximize-Their-Experience.html +- https://markets.financialcontent.com/woonsocketcall/article/gnwcq-2026-2-24-myfitnesspal-debuts-its-2026-winter-release +- https://9to5mac.com/2026/06/16/myfitnesspal-adds-ai-powered-coach-for-personalized-nutrition-guidance/ +- https://business.mammothtimes.com/mammothtimes/article/gnwcq-2026-1-7-myfitnesspal-launches-app-in-new-chatgpt-health-experience +- https://piunikaweb.com/2026/04/24/myfitnesspal-new-update-complaints/ +- https://mwm.ai/articles/myfitnesspal-v26-16-0-replaces-diary-with-new-ui-sparking-rating-drop-in-april-2026 +- https://www.healio.com/news/primary-care/20260804/ai-photobased-calorietracking-tools-underestimate-them-by-33 +- https://www.newswise.com/articles/photo-based-calorie-tracking-apps-may-underestimate-energy-in-meals +- https://www.eesel.ai/en/blog/cal-ai-pricing +- https://www.newswire.com/news/lose-it-finds-ai-powered-logging-boosts-weight-loss-success-and-22557702 +- https://www.fitbudd.com/post/lose-it-premium-review +- https://www.finanzen.net/nachricht/aktien/cronometer-launches-premium-photo-logging-fast-verified-nutrition-tracking-for-real-life-14808068 +- https://macrofactor.com/mm-july-2026/ +- https://macrofactor.com/mm-jan-2026/ +- https://macrofactor.com/mm-oct-2025/ +- https://macrofactor.com/ai-food-logging/ +- https://apps.apple.com/us/app/macrofactor-macro-tracker/id1553503471 +- https://www.similarweb.com/es/app/apple/6737156524 +- https://nutrola.app/en/blog/we-analyzed-50000-calorie-tracker-reviews-what-users-actually-complain-about-2026 (competitor, sentiment only) +- https://www.mycallie.app/en/blog/best-calorie-tracker-app-reddit +- https://www.noom.com/plans +- https://athletechnews.com/noom-microdose-glp1-rx-program-pricing-eligibility/ +- https://www.kff.org/public-opinion/poll-1-in-8-adults-say-they-are-currently-taking-a-glp-1-drug-for-weight-loss-diabetes-or-another-condition-even-as-half-say-the-drugs-are-difficult-to-afford/ +- https://digital-release.kxan.com/business/press-releases/cision/20260505FL48085/mynetdiary-launches-glp-1-companion-for-ozempic-wegovy-and-mounjaro-users +- https://strava.com/pricing +- https://www.t3.com/active/strava-and-runna-now-offer-a-joint-subscription-and-its-cheaper-than-buying-one-pair-of-running-shoes +- https://the5krunner.com/2026/10/14/is-runna-free/ +- https://www.sensai.fit/blog/fitbod-review-2026 +- https://www.sensai.fit/blog/future-app-review-2026 +- https://www.sensai.fit/blog/ladder-app-review-2026 +- https://www.sensai.fit/blog/hevy-review-2026 +- https://businesswire.com/news/home/20260508464188/en/WHOOP-Expands-Health-Platform-with-On-Demand-Clinician-Access-and-New-AI-Features +- https://www.wareable.com/wearable-tech/whoop-healthex-partnership-my-memory-ai-features-navigator-bands +- https://www.tomsguide.com/wellness/fitness/ouras-ai-powered-advisor-is-rolling-out-heres-what-it-means-for-you +- https://nutrola.app/en/blog/is-carbon-diet-coach-worth-it-2026 (competitor) +- https://toolradar.com/compare/streaks-vs-habitica +- https://pubmed.ncbi.nlm.nih.gov/31155473/ +- https://pmc.ncbi.nlm.nih.gov/articles/PMC7420735 +- https://www.fitbudd.com/fitness-industry-trends/ai-fitness-coaching-report From af3ce2d1cd8ad1ff0706362a599bd53b9552ddb3 Mon Sep 17 00:00:00 2001 From: Timothy Oluwatobi Ojebiyi Date: Wed, 4 Nov 2026 22:38:09 +0000 Subject: [PATCH 3/8] Add Google and Apple sign-in - iOS: Apple's native sheet (expo-apple-authentication) with a hashed nonce, exchanged with Supabase via signInWithIdToken; the name Apple shares on first sign-in is saved to the account. - Android and web, and Google everywhere: Supabase's sign-in page in a browser session (expo-web-browser), returning to /auth-callback with a one-time code. The Supabase client now uses the PKCE flow; the password reset screen already handled codes. - "Continue with Apple / Google" on the login screen and the onboarding sign-up step, shown only for providers switched on in Supabase (read from its public settings), so nothing appears until they're set up. The old "coming soon" buttons are gone. - Every sign-in method now finishes the same way (afterSignIn): create the backend user, named from the provider's profile, and save any onboarding answers. --- apps/mobile/app.json | 4 +- apps/mobile/app/(auth)/login.tsx | 52 ++------- apps/mobile/app/_layout.tsx | 3 +- apps/mobile/app/auth-callback.tsx | 44 ++++++++ apps/mobile/app/onboarding/signup.tsx | 4 + apps/mobile/components/auth/SocialSignIn.tsx | 90 ++++++++++++++++ apps/mobile/lib/postSignIn.ts | 18 ++++ apps/mobile/lib/socialAuth.ts | 105 +++++++++++++++++++ apps/mobile/lib/supabase.ts | 3 + apps/mobile/package.json | 3 + 10 files changed, 281 insertions(+), 45 deletions(-) create mode 100644 apps/mobile/app/auth-callback.tsx create mode 100644 apps/mobile/components/auth/SocialSignIn.tsx create mode 100644 apps/mobile/lib/postSignIn.ts create mode 100644 apps/mobile/lib/socialAuth.ts diff --git a/apps/mobile/app.json b/apps/mobile/app.json index bd7ef4d..176d307 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -94,7 +94,9 @@ "cameraPermission": false, "microphonePermission": false } - ] + ], + "expo-apple-authentication", + "expo-web-browser" ], "extra": { "eas": { diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx index bdd7568..1c6c9fa 100644 --- a/apps/mobile/app/(auth)/login.tsx +++ b/apps/mobile/app/(auth)/login.tsx @@ -1,29 +1,27 @@ import React, { useState } from 'react'; import { View, + Platform, Text, KeyboardAvoidingView, - Platform, ScrollView, Pressable, Alert, } from 'react-native'; import { Link, router } from 'expo-router'; import { supabase } from '@/lib/supabase'; -import { api } from '@/lib/api'; -import { useAuthStore } from '@/stores/authStore'; -import { syncOnboardingProfile } from '@/lib/onboardingProfile'; import { Button } from '@/components/ui/Button'; import { Input } from '@/components/ui/Input'; import { notify } from '@/lib/confirm'; import { sendPasswordReset } from '@/lib/passwordReset'; import { Colors } from '@/constants/colors'; +import { afterSignIn } from '@/lib/postSignIn'; +import { SocialSignIn } from '@/components/auth/SocialSignIn'; export default function LoginScreen() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); - const { setOnboardingComplete } = useAuthStore(); async function handleEmailLogin() { if (!email || !password) { @@ -32,15 +30,11 @@ export default function LoginScreen() { } setLoading(true); try { - const { error } = await supabase.auth.signInWithPassword({ email, password }); + const { data, error } = await supabase.auth.signInWithPassword({ email, password }); if (error) throw error; - await setOnboardingComplete(); - // Sync user record with backend (creates if first login) - await api.post('/auth/sync'); - // Save any plan answered before signing up (e.g. pending email confirmation) - await syncOnboardingProfile().catch(() => { - // Kept on the device and retried at the next login - }); + // Creates the backend user on first login and saves any plan answered + // before signing up (e.g. while the email was being confirmed) + await afterSignIn(data.session); router.replace('/(tabs)/'); } catch (err: any) { Alert.alert('Login failed', err.message ?? 'Something went wrong.'); @@ -126,36 +120,8 @@ export default function LoginScreen() { /> - {/* Divider */} - - - - or - - - - - {/* OAuth */} - -