Skip to content

PPP Mobile App — Architecture ​

Technology Stack ​

LayerTechnologyVersion
FrameworkExpo~52.0.47
RuntimeReact Native0.76.9
LanguageTypeScript^5.3.3
NavigationExpo Router~4.0.21
State ManagementZustand^5.0.5
Secure Storagereact-native-mmkv3.2.0
Async Storage@react-native-async-storage/async-storage1.23.1
API ClienttRPC v10 + React Query v4^10.45.2 / 4
Serialisationsuperjson2.2.1
StylingNativeWind (Tailwind for RN)4.1.23
Background Tasksexpo-task-manager + expo-background-task~12.0.6 / ~0.1.4
Locationexpo-location~18.0.10
Notificationsexpo-notifications~0.29.14
Healthreact-native-health^1.19.0
Build/CIExpo EASCLI >= 13.2.3
TestsJest + jest-expo^29.2.1 / ~52.0.2
Package managerpnpm >= 9(aligned with monorepo)

Authentication Flow ​

┌──────────────────────────────────────────────────────┐
│  app/index.tsx (Root Screen)                          │
│                                                       │
│  1. Renders react-native-webview pointing to WEB_URL  │
│  2. Injects JS that:                                  │
│     a. Reads all localStorage on page load            │
│     b. Overrides localStorage.setItem to intercept    │
│        Cognito idToken writes                         │
│     c. Observes URL changes via MutationObserver      │
│  3. On token found → postMessage({type:'tokenFound'}) │
│  4. Native onMessage handler:                         │
│     - Parses token from message                       │
│     - Calls sessionStore.setAccessToken(token)        │
│  5. On navigation to /dashboard, /ppp-dashboard, or   │
│     /my-profile:                                      │
│     - Injects token-check script                      │
│     - Replaces route to /(tabs)/dashboard             │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  sessionStore (Zustand + MMKV persist)                │
│  - accessToken: string | null                         │
│  - user: User | null                                  │
│  Persisted to MMKV under key "session-storage"        │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  trpcClient.ts                                        │
│  - httpBatchLink to TRPC_URL (from app.config.js)     │
│  - headers: { Authorization: Bearer <accessToken> }   │
│  - superjson transformer                              │
└──────────────────────────────────────────────────────┘

Security note: The token extraction mechanism injects JavaScript into the WebView to intercept Cognito's localStorage writes. This is tracked as issue #565 and is a known security debt — see SECURITY.md.


State Management ​

Zustand stores
├── sessionStore     (MMKV-persisted)
│   ├── accessToken  — Cognito idToken
│   └── user         — PPP User record from tRPC
  • subscribeWithSelector middleware enables selective subscription without re-renders.
  • persist middleware with MMKV adapter provides encrypted-at-rest storage.
  • tRPC hooks live in component trees; imperative calls (background tasks) use useSessionStore.getState().

Data Flow ​

Background Task (geofencing):
  Location event → TaskManager callback
    → useSessionStore.getState().user.id
    → trpcClient.ppp.getUserAssignedHospitals.query()
    → trpcClient.ppp.timesheets.create.mutate()
    → expo-notifications.scheduleNotificationAsync()

Foreground (tab screens):
  Component mount
    → trpc.<router>.<procedure>.useQuery()
    → TanStack Query cache
    → render

Auth bootstrap (tab layout):
  accessToken present
    → trpc.ppp.getCurrentUser.useQuery()
    → sessionStore.setUser(user)
    → permission flow (location → HealthKit → notifications)

Build Configuration ​

Build Profiles ​

ProfileBundle IDenvironment key
developmentcom.professionalperformanceportfolio.ppp.development"development" (explicit)
productioncom.professionalperformanceportfolio.pppnot set (uses APP_VARIANT env var instead)

Builds run via .github/workflows/mobile-build-native.yml on GitHub-hosted or self-hosted macOS runners using native xcodebuild archive (iOS) and ./gradlew bundleRelease (Android) — not EAS Cloud. See docs/site/mobile/cicd.md for the full workflow layout.

Runtime Configuration (app.config.js) ​

Environment variables injected at build time by the Mobile Build Native workflow:

  • WEB_URL — Base URL for the WebView (PPP web app)
  • TRPC_URL — tRPC Lambda Function URL

These are accessed at runtime via Constants.expoConfig?.extra?.TRPC_URL.

Native Permissions Requested ​

iOS (infoPlist):

  • NSCameraUsageDescription
  • NSPhotoLibraryUsageDescription / NSPhotoLibraryAddUsageDescription
  • UIBackgroundModes: ['location', 'fetch']

Android:

  • ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, ACCESS_BACKGROUND_LOCATION
  • FOREGROUND_SERVICE, FOREGROUND_SERVICE_LOCATION
  • CAMERA, READ_MEDIA_IMAGES
  • READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE

New Architecture ​

newArchEnabled: true — Expo 52 new architecture (JSI/Fabric) is enabled, which requires all native modules to be compatible.


app/
└── _layout.tsx          — Root: QueryClientProvider, TRPCProvider, SafeAreaProvider
    └── index.tsx         — WebView auth (unauthenticated)
    └── (tabs)/
        └── _layout.tsx   — TabLayout: auth guard, permission flow, HealthProvider, NotificationProvider
            └── [19 tab screens]

Routing uses Expo Router file-based routing. Typed routes are enabled (experiments.typedRoutes: true).


Background Task Architecture ​

The background location tasks are registered with expo-task-manager at module load time (top-level defineTask calls in location-service.ts). This is required by Expo's architecture — the task definition must run before the app is fully mounted.

Geofencing and continuous location updates use separate task names (#12509): HOSPITAL_GEOFENCE_TASK ('hospital-geofence-task', startGeofencingAsync) and CONTINUOUS_LOCATION_TASK ('continuous-location-task', startLocationUpdatesAsync). expo-task-manager keys registrations by name, and on iOS registering a name with a different consumer type replaces the old consumer — the geofence consumer's teardown stops monitoring every region and each new one re-fires "Entered". Never register both under one name. Both route to backgroundLocationTaskHandler, which dispatches on payload shape. The pre-#12509 shared name 'background-location-task' (LEGACY_SHARED_LOCATION_TASK) stays defined so persisted registrations on upgraded installs still deliver, and migrateLegacySharedLocationTask() unregisters it before any (re)registration.

The tree below is the historical sketch of the handler's work and predates native geofencing:

TaskManager.defineTask(<task name>, backgroundLocationTaskHandler)
  ├── On each location update:
  │   ├── For each assigned hospital:
  │   │   ├── geolib.isPointWithinRadius(pos, hospital, 50m)
  │   │   ├── ENTER detected:
  │   │   │   ├── hasTimesheetForToday() — tRPC query
  │   │   │   ├── getActiveTimesheetForHospital() — tRPC query
  │   │   │   ├── timesheets.create.mutate() — tRPC mutation
  │   │   │   └── Notifications.scheduleNotificationAsync()
  │   │   └── EXIT detected:
  │   │       ├── getActiveTimesheetForHospital() — tRPC query
  │   │       ├── timesheets.update.mutate() — tRPC mutation
  │   │       └── Notifications.scheduleNotificationAsync()

Concurrency protection uses a module-level notificationLock object keyed by hospital ID, with a 2-second timeout to release the lock (tracked as tech debt — see issue in TECH_DEBT.md).


Code Style ​

Prettier ​

The mobile app defines its own explicit Prettier configuration in mobile/ppp/.prettierrc.json rather than inheriting the root repository config. This prevents formatting drift if the root config changes.

The configuration mirrors the root .prettierrc.json as of project creation:

OptionValue
tabWidth2
printWidth90
useTabsfalse
semitrue
singleQuotetrue
bracketSpacingtrue
bracketSameLinefalse
arrowParens"avoid"
insertPragmafalse
trailingComma"all"

To format all files in the mobile app directory:

bash
cd mobile/ppp
pnpm prettier --write .

To check formatting without making changes:

bash
cd mobile/ppp
pnpm prettier --check .

Pre-Commit Hooks (husky + lint-staged) ​

The mobile/ppp directory uses husky and lint-staged to enforce code quality gates before every commit.

Setup ​

Hooks are installed automatically when dependencies are installed via the postinstall and prepare scripts in package.json:

bash
pnpm install

To install manually:

bash
pnpm husky install

Pre-commit Hook ​

The pre-commit hook (.husky/pre-commit) runs two gates in sequence:

  1. TypeScript type check — runs tsc --noEmit across the entire project. Any TypeScript error blocks the commit.
  2. lint-staged — runs ESLint and Prettier only on staged .ts/.tsx files.

lint-staged Configuration ​

Configured in package.json under the "lint-staged" key:

File patternCommands
*.{ts,tsx}eslint --fix --max-warnings=0, then prettier --write
*.{js,json,md}prettier --write

ESLint uses --max-warnings=0 so that warnings are treated as errors and block the commit.

Useful Scripts ​

ScriptDescription
pnpm lintRun ESLint across all files
pnpm lint:fixRun ESLint with auto-fix
pnpm formatRun Prettier auto-format on all files
pnpm format:checkCheck formatting without writing
pnpm typecheckRun tsc --noEmit type check

Bypassing Hooks (Emergency Only) ​

If you need to bypass hooks in an emergency (e.g. a broken generated file during an EAS prebuild):

bash
git commit --no-verify -m "your message"

This should be used only as a last resort. The CI pipeline performs the same checks and will fail if code does not pass lint, formatting, or type checks.

Internal documentation — org members only