# Code Examples & Implementation Snippets ## Overview This document provides concrete code examples and implementation snippets for all mobile optimization improvements. These examples can be directly used during implementation with minimal modifications. ## Mobile Settings Implementation ### Complete Mobile Settings Screen **File**: `frontend/src/features/settings/mobile/MobileSettingsScreen.tsx` ```tsx import React, { useState } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; import { GlassCard, MobileContainer, MobilePill } from '../../../shared-minimal/components/mobile'; import { useSettings } from '../hooks/useSettings'; interface ToggleSwitchProps { enabled: boolean; onChange: () => void; label: string; description?: string; } const ToggleSwitch: React.FC = ({ enabled, onChange, label, description }) => (

{label}

{description && (

{description}

)}
); interface ModalProps { isOpen: boolean; onClose: () => void; title: string; children: React.ReactNode; } const Modal: React.FC = ({ isOpen, onClose, title, children }) => { if (!isOpen) return null; return (

{title}

{children}
); }; export const MobileSettingsScreen: React.FC = () => { const { user, logout } = useAuth0(); const { settings, updateSetting } = useSettings(); const [showDataExport, setShowDataExport] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const handleLogout = () => { logout({ logoutParams: { returnTo: window.location.origin } }); }; const handleExportData = () => { // Implement data export functionality console.log('Exporting user data...'); setShowDataExport(false); }; const handleDeleteAccount = () => { // Implement account deletion console.log('Deleting account...'); setShowDeleteConfirm(false); }; return (
{/* Header */}

Settings

Manage your account and preferences

{/* Account Section */}

Account

{user?.picture && ( Profile )}

{user?.name}

{user?.email}

Member since {user?.updated_at ? new Date(user.updated_at).toLocaleDateString() : 'Unknown'}

{/* Notifications Section */}

Notifications

updateSetting('notifications', { ...settings.notifications, email: !settings.notifications.email })} label="Email Notifications" description="Receive updates via email" /> updateSetting('notifications', { ...settings.notifications, push: !settings.notifications.push })} label="Push Notifications" description="Receive mobile push notifications" /> updateSetting('notifications', { ...settings.notifications, maintenance: !settings.notifications.maintenance })} label="Maintenance Reminders" description="Get reminded about vehicle maintenance" />
{/* Appearance & Units Section */}

Appearance & Units

updateSetting('darkMode', !settings.darkMode)} label="Dark Mode" description="Switch to dark theme" />

Unit System

Currently using {settings.unitSystem === 'imperial' ? 'Miles & Gallons' : 'Kilometers & Liters'}

updateSetting('unitSystem', settings.unitSystem === 'imperial' ? 'metric' : 'imperial')} variant="secondary" />
{/* Data Management Section */}

Data Management

Download a copy of all your vehicle and fuel data

{/* Account Actions Section */}

Account Actions

{/* Data Export Modal */} setShowDataExport(false)} title="Export Data" >

This will create a downloadable file containing all your vehicle data, fuel logs, and preferences.

{/* Delete Account Confirmation */} setShowDeleteConfirm(false)} title="Delete Account" >

This action cannot be undone. All your data will be permanently deleted.

); }; ``` ## State Management Examples ### Enhanced Navigation Store **File**: `frontend/src/core/store/navigation.ts` ```tsx import { create } from 'zustand'; import { persist, createJSONStorage } from 'zustand/middleware'; export type MobileScreen = 'dashboard' | 'vehicles' | 'fuel' | 'settings'; export type VehicleSubScreen = 'list' | 'detail' | 'add' | 'edit'; interface NavigationHistory { screen: MobileScreen; vehicleSubScreen?: VehicleSubScreen; selectedVehicleId?: string | null; timestamp: number; metadata?: Record; } interface FormState { data: Record; timestamp: number; isDirty: boolean; } interface NavigationState { // Current navigation state activeScreen: MobileScreen; vehicleSubScreen: VehicleSubScreen; selectedVehicleId: string | null; // Navigation history for back button navigationHistory: NavigationHistory[]; // Form state preservation formStates: Record; // Loading and error states isNavigating: boolean; navigationError: string | null; // Actions navigateToScreen: (screen: MobileScreen, metadata?: Record) => void; navigateToVehicleSubScreen: (subScreen: VehicleSubScreen, vehicleId?: string, metadata?: Record) => void; goBack: () => boolean; canGoBack: () => boolean; saveFormState: (formId: string, data: any, isDirty?: boolean) => void; restoreFormState: (formId: string) => FormState | null; clearFormState: (formId: string) => void; clearAllFormStates: () => void; setNavigationError: (error: string | null) => void; } export const useNavigationStore = create()( persist( (set, get) => ({ // Initial state activeScreen: 'vehicles', vehicleSubScreen: 'list', selectedVehicleId: null, navigationHistory: [], formStates: {}, isNavigating: false, navigationError: null, // Navigation actions navigateToScreen: (screen, metadata = {}) => { const currentState = get(); set({ isNavigating: true, navigationError: null }); try { const historyEntry: NavigationHistory = { screen: currentState.activeScreen, vehicleSubScreen: currentState.vehicleSubScreen, selectedVehicleId: currentState.selectedVehicleId, timestamp: Date.now(), metadata, }; set({ activeScreen: screen, vehicleSubScreen: screen === 'vehicles' ? 'list' : currentState.vehicleSubScreen, selectedVehicleId: screen === 'vehicles' ? currentState.selectedVehicleId : null, navigationHistory: [...currentState.navigationHistory, historyEntry].slice(-10), isNavigating: false, }); } catch (error) { set({ navigationError: error instanceof Error ? error.message : 'Navigation failed', isNavigating: false }); } }, navigateToVehicleSubScreen: (subScreen, vehicleId = null, metadata = {}) => { const currentState = get(); set({ isNavigating: true, navigationError: null }); try { const historyEntry: NavigationHistory = { screen: currentState.activeScreen, vehicleSubScreen: currentState.vehicleSubScreen, selectedVehicleId: currentState.selectedVehicleId, timestamp: Date.now(), metadata, }; set({ vehicleSubScreen: subScreen, selectedVehicleId: vehicleId || currentState.selectedVehicleId, navigationHistory: [...currentState.navigationHistory, historyEntry].slice(-10), isNavigating: false, }); } catch (error) { set({ navigationError: error instanceof Error ? error.message : 'Navigation failed', isNavigating: false }); } }, goBack: () => { const currentState = get(); const lastEntry = currentState.navigationHistory[currentState.navigationHistory.length - 1]; if (lastEntry) { set({ activeScreen: lastEntry.screen, vehicleSubScreen: lastEntry.vehicleSubScreen || 'list', selectedVehicleId: lastEntry.selectedVehicleId, navigationHistory: currentState.navigationHistory.slice(0, -1), isNavigating: false, navigationError: null, }); return true; } return false; }, canGoBack: () => { return get().navigationHistory.length > 0; }, // Form state management saveFormState: (formId, data, isDirty = true) => { const currentState = get(); const formState: FormState = { data, timestamp: Date.now(), isDirty, }; set({ formStates: { ...currentState.formStates, [formId]: formState, }, }); }, restoreFormState: (formId) => { const state = get().formStates[formId]; const maxAge = 2 * 60 * 60 * 1000; // 2 hours if (state && Date.now() - state.timestamp < maxAge) { return state; } // Clean up old state if (state) { get().clearFormState(formId); } return null; }, clearFormState: (formId) => { const currentState = get(); const newFormStates = { ...currentState.formStates }; delete newFormStates[formId]; set({ formStates: newFormStates }); }, clearAllFormStates: () => { set({ formStates: {} }); }, setNavigationError: (error) => { set({ navigationError: error }); }, }), { name: 'motovaultpro-mobile-navigation', storage: createJSONStorage(() => localStorage), partialize: (state) => ({ activeScreen: state.activeScreen, vehicleSubScreen: state.vehicleSubScreen, selectedVehicleId: state.selectedVehicleId, formStates: state.formStates, }), } ) ); ``` ### Form State Hook Implementation **File**: `frontend/src/core/hooks/useFormState.ts` ```tsx import { useState, useEffect, useCallback, useRef } from 'react'; import { useNavigationStore } from '../store/navigation'; import { debounce } from 'lodash'; export interface UseFormStateOptions { formId: string; defaultValues: T; autoSave?: boolean; saveDelay?: number; onRestore?: (data: T) => void; onSave?: (data: T) => void; validate?: (data: T) => Record | null; } export interface FormStateReturn { formData: T; updateFormData: (updates: Partial) => void; setFormData: (data: T) => void; resetForm: () => void; submitForm: () => Promise; hasChanges: boolean; isRestored: boolean; isSaving: boolean; errors: Record; isValid: boolean; } export const useFormState = >({ formId, defaultValues, autoSave = true, saveDelay = 1000, onRestore, onSave, validate, }: UseFormStateOptions): FormStateReturn => { const { saveFormState, restoreFormState, clearFormState } = useNavigationStore(); const [formData, setFormDataState] = useState(defaultValues); const [hasChanges, setHasChanges] = useState(false); const [isRestored, setIsRestored] = useState(false); const [isSaving, setIsSaving] = useState(false); const [errors, setErrors] = useState>({}); const initialDataRef = useRef(defaultValues); const formDataRef = useRef(formData); // Update ref when formData changes useEffect(() => { formDataRef.current = formData; }, [formData]); // Validation const validateForm = useCallback((data: T) => { if (!validate) return {}; const validationErrors = validate(data); return validationErrors || {}; }, [validate]); // Restore form state on mount useEffect(() => { const restoredState = restoreFormState(formId); if (restoredState && !isRestored) { const restoredData = { ...defaultValues, ...restoredState.data }; setFormDataState(restoredData); setHasChanges(restoredState.isDirty); setIsRestored(true); if (onRestore) { onRestore(restoredData); } } }, [formId, restoreFormState, defaultValues, isRestored, onRestore]); // Auto-save with debounce const debouncedSave = useCallback( debounce(async (data: T, isDirty: boolean) => { if (!autoSave || !isDirty) return; try { setIsSaving(true); saveFormState(formId, data, isDirty); if (onSave) { await onSave(data); } } catch (error) { console.warn('Form auto-save failed:', error); } finally { setIsSaving(false); } }, saveDelay), [autoSave, saveDelay, formId, saveFormState, onSave] ); // Trigger auto-save when form data changes useEffect(() => { if (hasChanges) { const validationErrors = validateForm(formData); setErrors(validationErrors); debouncedSave(formData, hasChanges); } }, [formData, hasChanges, validateForm, debouncedSave]); const updateFormData = useCallback((updates: Partial) => { setFormDataState((current) => { const updated = { ...current, ...updates }; const hasActualChanges = JSON.stringify(updated) !== JSON.stringify(initialDataRef.current); setHasChanges(hasActualChanges); return updated; }); }, []); const setFormData = useCallback((data: T) => { setFormDataState(data); const hasActualChanges = JSON.stringify(data) !== JSON.stringify(initialDataRef.current); setHasChanges(hasActualChanges); }, []); const resetForm = useCallback(() => { setFormDataState(defaultValues); setHasChanges(false); setErrors({}); clearFormState(formId); initialDataRef.current = { ...defaultValues }; }, [defaultValues, formId, clearFormState]); const submitForm = useCallback(async () => { const validationErrors = validateForm(formDataRef.current); setErrors(validationErrors); if (Object.keys(validationErrors).length > 0) { throw new Error('Form validation failed'); } try { setHasChanges(false); clearFormState(formId); initialDataRef.current = { ...formDataRef.current }; if (onSave) { await onSave(formDataRef.current); } } catch (error) { setHasChanges(true); // Restore changes state on error throw error; } }, [validateForm, formId, clearFormState, onSave]); const isValid = Object.keys(errors).length === 0; return { formData, updateFormData, setFormData, resetForm, submitForm, hasChanges, isRestored, isSaving, errors, isValid, }; }; ``` ## Token Management Examples ### Enhanced API Client with 401 Retry **File**: `frontend/src/core/api/enhancedClient.ts` ```tsx import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; interface TokenManager { refreshToken(): Promise; isRefreshing(): boolean; addFailedRequest(request: () => Promise): void; } class AuthTokenManager implements TokenManager { private static instance: AuthTokenManager; private _isRefreshing = false; private failedQueue: Array<{ resolve: (token: string) => void; reject: (error: Error) => void; }> = []; private getAccessTokenSilently: any; constructor(getAccessTokenSilently: any) { this.getAccessTokenSilently = getAccessTokenSilently; } static getInstance(getAccessTokenSilently?: any): AuthTokenManager { if (!AuthTokenManager.instance && getAccessTokenSilently) { AuthTokenManager.instance = new AuthTokenManager(getAccessTokenSilently); } return AuthTokenManager.instance; } async refreshToken(): Promise { if (this._isRefreshing) { return new Promise((resolve, reject) => { this.failedQueue.push({ resolve, reject }); }); } this._isRefreshing = true; try { const token = await this.getAccessTokenSilently({ cacheMode: 'off', timeoutInSeconds: 20, }); // Process queued requests this.failedQueue.forEach(({ resolve }) => resolve(token)); this.failedQueue = []; return token; } catch (error) { // Reject queued requests this.failedQueue.forEach(({ reject }) => reject(error as Error)); this.failedQueue = []; throw error; } finally { this._isRefreshing = false; } } isRefreshing(): boolean { return this._isRefreshing; } addFailedRequest(callback: () => Promise): void { this.failedQueue.push({ resolve: () => callback(), reject: (error) => Promise.reject(error), }); } } export const createEnhancedApiClient = (getAccessTokenSilently: any): AxiosInstance => { const tokenManager = AuthTokenManager.getInstance(getAccessTokenSilently); const client = axios.create({ baseURL: process.env.REACT_APP_API_URL || '/api', timeout: 10000, headers: { 'Content-Type': 'application/json', }, }); // Request interceptor - inject tokens client.interceptors.request.use( async (config) => { try { // Don't add token if already refreshing or if this is a retry if (!config._retry && !tokenManager.isRefreshing()) { const token = await getAccessTokenSilently({ cacheMode: 'on', timeoutInSeconds: 15, }); if (token) { config.headers = config.headers || {}; config.headers.Authorization = `Bearer ${token}`; } } } catch (error) { console.warn('Token acquisition failed, proceeding without token:', error); } return config; }, (error) => Promise.reject(error) ); // Response interceptor - handle 401s with token refresh retry client.interceptors.response.use( (response: AxiosResponse) => response, async (error) => { const originalRequest = error.config; // Handle 401 responses with token refresh if (error.response?.status === 401 && !originalRequest._retry) { originalRequest._retry = true; try { console.log('401 detected, attempting token refresh...'); const newToken = await tokenManager.refreshToken(); // Update the failed request with new token originalRequest.headers = originalRequest.headers || {}; originalRequest.headers.Authorization = `Bearer ${newToken}`; // Retry the original request return client(originalRequest); } catch (refreshError) { console.error('Token refresh failed:', refreshError); // Clear any stored tokens and redirect to login localStorage.clear(); window.location.href = '/'; return Promise.reject(refreshError); } } // Enhanced mobile error handling if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) { const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ); if (isMobile) { error.message = 'Connection timeout. Please check your network and try again.'; } } return Promise.reject(error); } ); return client; }; // Usage example export const useApiClient = () => { const { getAccessTokenSilently } = useAuth0(); return useMemo(() => { return createEnhancedApiClient(getAccessTokenSilently); }, [getAccessTokenSilently]); }; ``` ## Mobile Component Examples ### Enhanced Add Vehicle Form with State Persistence **File**: `frontend/src/features/vehicles/mobile/EnhancedAddVehicleScreen.tsx` ```tsx import React, { useCallback } from 'react'; import { ArrowLeft, Save } from 'lucide-react'; import { useFormState } from '../../../core/hooks/useFormState'; import { useNavigationStore } from '../../../core/store/navigation'; import { GlassCard, MobileContainer, MobilePill } from '../../../shared-minimal/components/mobile'; interface VehicleFormData { year: string; make: string; model: string; trim: string; vin: string; licensePlate: string; nickname: string; color: string; } interface EnhancedAddVehicleScreenProps { onVehicleAdded: () => void; } export const EnhancedAddVehicleScreen: React.FC = ({ onVehicleAdded, }) => { const { goBack } = useNavigationStore(); const validateForm = useCallback((data: VehicleFormData) => { const errors: Record = {}; if (!data.year || parseInt(data.year) < 1900 || parseInt(data.year) > new Date().getFullYear() + 1) { errors.year = 'Please enter a valid year'; } if (!data.make.trim()) { errors.make = 'Make is required'; } if (!data.model.trim()) { errors.model = 'Model is required'; } if (data.vin && data.vin.length !== 17) { errors.vin = 'VIN must be 17 characters'; } if (!data.vin.trim() && !data.licensePlate.trim()) { errors.licensePlate = 'Either VIN or License Plate is required'; } return Object.keys(errors).length > 0 ? errors : null; }, []); const { formData, updateFormData, resetForm, submitForm, hasChanges, isRestored, isSaving, errors, isValid, } = useFormState({ formId: 'add-vehicle', defaultValues: { year: '', make: '', model: '', trim: '', vin: '', licensePlate: '', nickname: '', color: '', }, validate: validateForm, onRestore: (data) => { console.log('Form data restored:', data); }, }); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!isValid) { return; } try { // Simulate API call await new Promise(resolve => setTimeout(resolve, 1000)); await submitForm(); onVehicleAdded(); } catch (error) { console.error('Error adding vehicle:', error); // Form state is preserved on error } }; const handleBack = () => { if (hasChanges) { const confirmLeave = window.confirm( 'You have unsaved changes. Are you sure you want to leave? Your changes will be saved as a draft.' ); if (!confirmLeave) return; } goBack(); }; return (
{/* Header */}

Add Vehicle

{isRestored && (

Draft restored

)}
{isSaving && (
Saving...
)}
{/* Basic Information */}

Basic Information

updateFormData({ year: e.target.value })} className={`w-full p-3 border rounded-lg ${ errors.year ? 'border-red-300' : 'border-slate-300' }`} /> {errors.year && (

{errors.year}

)}
updateFormData({ make: e.target.value })} className={`w-full p-3 border rounded-lg ${ errors.make ? 'border-red-300' : 'border-slate-300' }`} /> {errors.make && (

{errors.make}

)}
updateFormData({ model: e.target.value })} className={`w-full p-3 border rounded-lg ${ errors.model ? 'border-red-300' : 'border-slate-300' }`} /> {errors.model && (

{errors.model}

)}
updateFormData({ trim: e.target.value })} className="w-full p-3 border border-slate-300 rounded-lg" />
{/* Identification */}

Identification

updateFormData({ vin: e.target.value.toUpperCase() })} maxLength={17} className={`w-full p-3 border rounded-lg font-mono text-sm ${ errors.vin ? 'border-red-300' : 'border-slate-300' }`} /> {errors.vin && (

{errors.vin}

)}
updateFormData({ licensePlate: e.target.value.toUpperCase() })} className={`w-full p-3 border rounded-lg ${ errors.licensePlate ? 'border-red-300' : 'border-slate-300' }`} /> {errors.licensePlate && (

{errors.licensePlate}

)}
updateFormData({ nickname: e.target.value })} className="w-full p-3 border border-slate-300 rounded-lg" />
{/* Form Actions */}
{hasChanges && (

Changes are being saved automatically

)}
); }; ``` ## App Integration Examples ### Updated App.tsx with Enhanced Navigation **File**: `frontend/src/App.tsx` (key sections) ```tsx import React, { useEffect } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; import { useNavigationStore } from './core/store/navigation'; import { useUserStore } from './core/store/user'; import { MobileSettingsScreen } from './features/settings/mobile/MobileSettingsScreen'; import { EnhancedAddVehicleScreen } from './features/vehicles/mobile/EnhancedAddVehicleScreen'; const MobileApp: React.FC = () => { const { user, isAuthenticated, isLoading } = useAuth0(); const { activeScreen, vehicleSubScreen, selectedVehicleId, navigateToScreen, navigateToVehicleSubScreen, goBack, canGoBack, navigationError, } = useNavigationStore(); const { setUserProfile } = useUserStore(); // Update user profile when authenticated useEffect(() => { if (isAuthenticated && user) { setUserProfile(user); } }, [isAuthenticated, user, setUserProfile]); // Handle mobile back button and navigation errors useEffect(() => { const handlePopState = (event: PopStateEvent) => { event.preventDefault(); if (canGoBack()) { goBack(); } }; const handleNavigationError = () => { if (navigationError) { console.error('Navigation error:', navigationError); // Could show toast notification here } }; window.addEventListener('popstate', handlePopState); handleNavigationError(); return () => { window.removeEventListener('popstate', handlePopState); }; }, [goBack, canGoBack, navigationError]); const handleVehicleSelect = useCallback((vehicleId: string) => { navigateToVehicleSubScreen('detail', vehicleId, { source: 'vehicle-list' }); }, [navigateToVehicleSubScreen]); const handleAddVehicle = useCallback(() => { navigateToVehicleSubScreen('add', null, { source: 'vehicle-list' }); }, [navigateToVehicleSubScreen]); const handleBackToList = useCallback(() => { navigateToVehicleSubScreen('list', null, { source: 'back-navigation' }); }, [navigateToVehicleSubScreen]); const handleVehicleAdded = useCallback(() => { navigateToVehicleSubScreen('list', null, { source: 'vehicle-added' }); }, [navigateToVehicleSubScreen]); // Show loading screen while Auth0 initializes if (isLoading) { return (

Loading MotoVaultPro...

); } // Show login screen if not authenticated if (!isAuthenticated) { return (

MotoVaultPro

Track your vehicles and fuel efficiency

); } // Main mobile app interface return (
{/* Navigation Error Banner */} {navigationError && (

Navigation Error

{navigationError}

)} {/* Screen Content */} {renderActiveScreen()} {/* Bottom Navigation */}
); // Screen rendering logic function renderActiveScreen() { switch (activeScreen) { case 'vehicles': return renderVehiclesScreen(); case 'fuel': return ; case 'dashboard': return ; case 'settings': return ; default: return renderVehiclesScreen(); } } function renderVehiclesScreen() { switch (vehicleSubScreen) { case 'list': return ( ); case 'detail': return ( ); case 'add': return ( ); default: return ( ); } } }; ``` These code examples provide concrete, implementable solutions for all aspects of the mobile optimization plan. Each example includes proper error handling, TypeScript types, and integration with the existing architecture.