CoolFace
Apppublic

hardik1231312/conflictData

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes
FRONTEND_API_IMPLEMENTATION.md391 linesDownload Raw Back to root
1# Frontend API Integration Guide2 3This document explains, in implementation detail, how the frontend consumes backend APIs and real-time streams, and how each payload is transformed into UI behavior.4 5## 1) Frontend Architecture Overview6 7The frontend is a React SPA with two routes:8 9- `/` -> Tactical dashboard (`Dashboard.jsx`)10- `/sitrep` -> Strategic analytics page (`AnalyticsPage.jsx`)11 12Key orchestration files:13 14- `frontend/src/config.js`: selects API base URL.15- `frontend/src/Dashboard.jsx`: loads tactical data + subscribes to WebSocket.16- `frontend/src/components/AnalyticsPage.jsx`: loads strategic data + reads SSE AI stream.17- `frontend/src/hooks/useTacticalWS.js`: resilient WebSocket connection and reconnect.18 19## 2) API Base URL Resolution20 21File: `frontend/src/config.js`22 23Behavior:24 25- If hostname is `localhost` or `127.0.0.1`, API base is hardcoded to:26  - `https://hardik1231312-conflictdata.hf.space`27- Otherwise, base is empty string `''` (same-origin relative requests).28 29Implementation impact:30 31- Local development still targets deployed backend unless this config is changed.32- Production uses relative paths like `/api/v1/...`.33 34## 3) Route-Level Data Responsibilities35 36### `/` Dashboard (`frontend/src/Dashboard.jsx`)37 38Owns:39 40- Tactical event timeline41- Threat counters42- Map intelligence layers43- Flash alerts44- Live connectivity status45 46Data sources:47 48- One-time bootstrapping REST calls on mount.49- Continuous WebSocket stream (`/api/v1/ws`) for live event inserts.50 51### `/sitrep` Strategic Analytics (`frontend/src/components/AnalyticsPage.jsx`)52 53Owns:54 55- Situation briefing summary56- Strategic forecast57- Theater cards58- AI streaming report terminal59 60Data sources:61 62- Polling REST calls every 60s for strategic snapshots.63- On-demand SSE stream for AI analyst output (`/api/v1/ai/analyze`).64 65## 4) Dashboard API Integration (Detailed)66 67File: `frontend/src/Dashboard.jsx`68 69### 4.1 Initial REST bootstrap (`useEffect` on mount)70 71The dashboard executes all requests concurrently using `Promise.all` with a `safeFetch` wrapper.72 73Endpoints called:74 751. `GET /api/v1/stats/stats`762. `GET /api/v1/conflicts/ongoing?limit=100`773. `GET /api/v1/intel/monitor`784. `GET /api/v1/intel/frontlines`795. `GET /api/v1/intel/hotspots`806. `GET /api/v1/intel/trends`817. `GET /api/v1/intel/sitrep`828. `GET /api/v1/intel/theaters`83 84`safeFetch` behavior:85 86- Returns parsed JSON when `res.ok`.87- Returns `null` for non-2xx or network errors.88- Prevents one failing endpoint from crashing the whole init sequence.89 90### 4.2 State mapping from responses91 92State variables:93 94- `events`: set from `eventsRes.data` (ongoing conflicts endpoint).95- `stats`:96  - `total_events` <- `statsRes.total_events`97  - `high_severity` <- `statsRes.by_severity.HIGH`98  - `sitrep` <- full `sitrepRes` object99  - `active_wars` currently fixed `0` (not dynamically sourced)100- `layerData`:101  - `monitor` <- `monitorRes`102  - `frontlines` <- `frontRes`103  - `hotspots` <- `hotRes`104  - `trends` <- `trendRes`105  - `theaters` <- `theaterRes`106 107All layer arrays are normalized with:108 109- `safeArr = arr => Array.isArray(arr) ? arr : []`110 111This guards against null/error shapes.112 113### 4.3 Layer counts derived from API payloads114 115Layer metadata in `layers` state is updated after bootstrap:116 117- `kinetic.count` <- ongoing events length118- `theaters.count` <- theaters length119- `priority.count` <- monitor length120- `frontlines.count` <- frontlines length121- `hotspots.count` <- hotspots length122- `surges.count` <- trends length123- `civilians.count` <- events with `fatalities_civilians > 0`124 125These counts drive `LayerManager` telemetry badges.126 127### 4.4 Real-time updates from WebSocket128 129Hook: `useTacticalWS` with callback:130 131- Prepends new event into `events` (keeps max ~100 items):132  - `[newEvent, ...prev.slice(0, 99)]`133- Triggers flash alert for high-priority events when:134  - `newEvent.severity_score >= 7.5` OR `newEvent.priority === true`135- Increments:136  - `stats.total_events` by 1137  - `stats.high_severity` by 1 when `severity_score >= 8.5`138- Updates `kinetic` layer count.139 140Flash alert UI:141 142- Shows `title`, `city`, `country`.143- Auto-dismisses after 8 seconds.144 145## 5) WebSocket Transport Implementation146 147File: `frontend/src/hooks/useTacticalWS.js`148 149### 5.1 URL selection150 151- If `API_BASE` starts with `http`, converts to WS:152  - `http` -> `ws`153  - `https` -> `wss`154  - appends `/api/v1/ws`155- Otherwise builds same-origin URL:156  - `${protocol}//${window.location.host}/api/v1/ws`157 158### 5.2 Lifecycle and resiliency159 160- On mount: call `connect()`.161- On open:162  - set status `ONLINE`163  - clear reconnect timer if active164- On message:165  - parse JSON and forward to callback166- On close:167  - set status `OFFLINE`168  - schedule reconnect after 5 seconds169- On error:170  - close socket (which triggers reconnect flow)171- On unmount:172  - close socket cleanly173 174Status is surfaced to dashboard header as `COMMS`.175 176## 6) How API Data Is Rendered in UI Components177 178### 6.1 TacticalMap (`frontend/src/components/TacticalMap.jsx`)179 180Consumes:181 182- `events` (ongoing + websocket inserts)183- `layerData` (monitor/frontlines/hotspots/trends/theaters)184- `layers` toggles/opacities185 186Render rules by API source:187 188- `/conflicts/ongoing` + WS events:189  - Kinetic `Marker`s at `[lat, lon]`190  - popup fields: `title`, `severity_score`, `country_iso3`, `actor1`, `weapon`, `fatalities`, `notes`191- `/intel/frontlines`:192  - large `Circle` overlays with `primary_engagement`, `country`193- `/intel/hotspots`:194  - heat-style `Circle` overlays195- `/intel/trends`:196  - surge circles built from derived centroids:197    - For each trend country, average `lat/lon` of matching current `events`198    - display `surge_percentage`199- `/intel/monitor`:200  - priority markers201- `/intel/theaters`:202  - strategic theater circles using:203    - `center_lat`, `center_lon`, `spread_km`, `stability_rating`, `intensity`, `dominant_actor`, `total_events`204  - visual severity color based on stability and intensity.205 206Interaction using frontend routing + API context:207 208- `DEEP ANALYZE SECTOR` button builds a context string from selected event fields and navigates:209  - `navigate('/sitrep', { state: { context } })`210- This context is later sent to `/api/v1/ai/analyze?context=...`.211 212### 6.2 TacticalFeed (`frontend/src/components/TacticalFeed.jsx`)213 214Consumes `events`.215 216Uses API fields:217 218- Event categorization: `event_type`219- Time display: `event_time`220- Card title: `title`221- Telemetry chips: `actor1`, `weapon`, `fatalities`222- Location: `city`, `country`223- Severity styling: `severity_score`224 225Selection behavior:226 227- Clicking a feed card sends selected event to parent.228- Parent recenters map and highlights selected card.229 230### 6.3 CombatTicker (`frontend/src/components/CombatTicker.jsx`)231 232Consumes `events`.233 234Uses:235 236- `event_type`, `title`, `city`, `country_iso3`237 238Output:239 240- Scrolling duplicated ticker text loop.241 242### 6.4 LayerManager (`frontend/src/components/LayerManager.jsx`)243 244No direct API calls.245 246Consumes counts/opacities derived from API data in parent state.247 248Purpose:249 250- Toggle map layers.251- Adjust per-layer opacity.252- Show live count badges populated from API-backed state.253 254## 7) Strategic Analytics Page Integration255 256File: `frontend/src/components/AnalyticsPage.jsx`257 258### 7.1 Polling REST data (every 60 seconds)259 260Endpoints:261 262- `GET /api/v1/intel/sitrep`263- `GET /api/v1/intel/forecast`264- `GET /api/v1/intel/theaters`265 266State mapping:267 268- `sitrep` <- sitrep payload269- `forecast` <- forecast payload270- `theaters` <- theaters array271 272UI bindings:273 274- Situation Briefing block <- `sitrep.summary`275- Threat intensity badge <- `sitrep.intensity`276- Forecast card <- `forecast.forecast`, `forecast.risk_level`277- Theater cards <- `theaters[*]` fields (`name`, `intensity`, `dominant_actor`, `stability_rating`)278- Right-side stat mini-cards:279  - active ops = `theaters.length`280  - actors = `sitrep.stats.most_active_actor ? 1 : 0`281  - intel feed = `sitrep.stats.total_events`282  - fatalities = `sitrep.stats.total_fatalities`283 284### 7.2 AI stream ingestion (`/api/v1/ai/analyze`)285 286Trigger:287 288- On page load (and when navigation state changes), `startAnalysis(context)` is called.289 290Context mode:291 292- If `location.state.context` exists:293  - `GET /api/v1/ai/analyze?context=<encoded>`294- Else:295  - `GET /api/v1/ai/analyze`296 297Streaming parser:298 299- Reads response body with `ReadableStream` reader.300- Splits incoming text by newline.301- Extracts lines prefixed with `data: `.302- Appends token text progressively to `report` state.303 304Error behavior:305 306- Appends `[CRITICAL ERROR: INTELLIGENCE LINK SEVERED]`.307 308### 7.3 AIAnalyst terminal rendering309 310File: `frontend/src/components/AIAnalyst.jsx`311 312Consumes:313 314- `report`, `isAnalyzing`, `provider`315 316Behavior:317 318- Auto-scroll as report grows.319- Animated status text while streaming.320- Confidence meter:321  - grows during analysis322  - fixed to 96.4 on completion323 324## 8) Unused API-Capable Component325 326File: `frontend/src/components/ConflictRollup.jsx`327 328Contains integration to:329 330- `GET /api/v1/active-conflicts` (with 60s refresh)331 332Current status:333 334- Not imported or rendered by any active route/component.335- API call is implemented but dormant unless this component is mounted.336 337## 9) End-to-End Data Flow Summary338 3391. App routes user to Dashboard or Sitrep page.3402. Dashboard:341   - pulls tactical baseline snapshots via REST342   - opens WS connection for delta updates343   - merges WS events into the same `events` list3443. Map/feed/ticker consume shared `events` and `layerData`.3454. User can select a map event and jump to Sitrep with generated context.3465. Sitrep page:347   - polls strategic snapshots every minute348   - streams AI analysis via SSE endpoint349   - progressively renders analyst text in terminal panel.350 351## 10) API Contract Dependencies by Field352 353Critical fields expected by frontend rendering:354 355- Map markers: `lat`, `lon`, `event_id`356- Severity visuals: `severity_score`357- Feed labels: `event_type`, `title`, `event_time`358- Location labels: `city`, `country`, `country_iso3`359- Theaters overlay: `center_lat`, `center_lon`, `spread_km`, `stability_rating`, `intensity`360- Trend overlays: `country_iso3`, `surge_percentage`361- Sitrep cards: `summary`, `intensity`, `stats.total_events`, `stats.total_fatalities`362- Forecast card: `forecast`, `risk_level`363- WS alerting: `priority` boolean (or fallback from severity score)364 365If these fields are missing/null, affected UI areas degrade (empty markers, broken centering, missing labels, or fallback placeholders).366 367## 11) Current Frontend Resilience Patterns368 369Implemented:370 371- `safeFetch` null-guards in dashboard bootstrap.372- `Array.isArray` guards for layer arrays.373- WebSocket auto-reconnect every 5 seconds.374- Graceful placeholder text on missing strategic data.375- SSE stream appends partial data without blocking full completion.376 377Not yet implemented:378 379- Central API client abstraction (calls are inline).380- Runtime schema validation for payloads.381- Abort controllers for in-flight request cancellation on unmount.382- Backoff/jitter strategy for HTTP retries.383- Unified toast/error surface for users (errors are mostly `console.error`).384 385## 12) Practical Implementation Notes386 387- The UI references some fields not guaranteed by all endpoints, such as `weapon`; backend payloads should include or frontend should guard further.388- Dashboard currently fetches `sitrep` as part of tactical boot and stores it inside `stats.sitrep` rather than a dedicated state object.389- Analytics polling and analysis streaming are independent; strategic cards can refresh while report stream runs.390 391