Skip to main content
This page documents the React components used in the Fleet Dashboard. Components are organized from the navigation wrapper down to individual map components.

FleetManagement.tsx

The navigation wrapper component that provides the pill-style navigation bar and routes between different Fleet Management modules.

Purpose

  • Renders the navigation header with pill-style buttons
  • Handles client-side routing between fleet modules
  • Passes navigation callbacks to child components
  • Displays the appropriate module based on current URL path

Props

interface FleetManagementProps {
  onNavigateToTracking?: (loadId: string) => void;
  onNavigateToTractor?: (tractorId: string) => void;
}
PropTypeDescription
onNavigateToTracking(loadId: string) => voidCallback when user wants to navigate to tracking page
onNavigateToTractor(tractorId: string) => voidCallback when user wants to navigate to tractor details
The component defines a static array of navigation items:
IDLabelIconRoute
overviewDashboardLayoutDashboard/fleet
driversDriver ManagementUser/fleet/drivers
tractorsTractor ManagementTruck/fleet/tractors
trailersTrailer ManagementContainer/fleet/trailers
ptaPredicted Time AvailableClock/fleet/pta

renderContent

Internal function that renders the appropriate child component based on router.pathname:
const renderContent = () => {
  switch (currentPath) {
    case '/fleet/drivers':
      return <DriverManagement ... />;
    case '/fleet/tractors':
      return <TractorManagement ... />;
    case '/fleet/trailers':
      return <TrailerManagement />;
    case '/fleet/pta':
      return <PredictedTimeAvailable />;
    case '/fleet':
    default:
      return <UnifiedFleetDashboard />;
  }
};

Styling

The navigation uses a modern “pills” style with:
  • Active state: Yellow gradient background with shadow
  • Inactive state: Semi-transparent white with border
  • Rounded full (pill shape)
  • Hover transitions with shadow effects

UnifiedFleetDashboard.tsx

The main dashboard component that displays KPI cards, interactive maps, fleet panels, and search functionality.

Purpose

  • Display real-time fleet statistics (KPIs)
  • Provide interactive map views for tractors, trailers, and drivers
  • Enable search across drivers, vehicles, trailers, orders, and movements
  • Show fleet summary panels with filterable lists

Dependencies

ImportPurpose
useUnifiedFleetDataHook for fetching and managing fleet data
ConnectionStatusIndicatorShows SSE connection status
LiveVehicleMapInteractive tractor/vehicle map
LiveTrailerMapInteractive trailer map
shadcn/ui componentsCard, Button, Badge, Tabs, Input, Select

State Management

StateTypeDefaultPurpose
activeTabstring'dashboard'Current tab (dashboard/alerts)
searchQuerystring''Search input value
vehicleMetricFilter'all' | 'active' | 'inactive' | 'lowFuel''all'Vehicle filter
mapView'tractors' | 'trailers' | 'drivers''tractors'Map view mode
dispatcherFilterstring'all'Dispatcher filter for tractors
StateTypePurpose
isSearchingbooleanLoading indicator for API search
searchErrorstring | nullError message from search
searchResultIds{ drivers, vehicles, trailers }IDs returned from order/movement search
StateTypePurpose
movementsany[]Movements data for vehicle-load mapping
orderIdToCustomerNameMap<string, string>Cache of order ID to customer name

Key useMemo Computations

Maps vehicle_id to active load information for display in map popups.Returns: Map<string, { orderId, movementId, origin, destination, customerName }>Logic:
  1. Iterates through movements
  2. Finds vehicle by matching tractor_number to movement.tractor_id
  3. Extracts pickup/delivery stops for origin/destination
  4. Gets customer name from order ID cache
Creates multiple mappings from various driver ID formats to full name.Returns: Map<string, string>Maps by:
  • driver_id (with/without drv_ prefix)
  • source_id (with/without drv_ prefix)
  • username
  • All in lowercase variants
Why multiple ID formats? Different data sources use different ID formats for the same driver:
  • Vehicles may reference drivers as "drv_12345" or just "12345"
  • Backend may use source_id while frontend uses driver_id
  • This mapping normalizes all formats for reliable lookups
Filters vehicles based on search query, metric filter, and dispatcher filter.Filters applied:
  • Search result IDs (from API order/movement search)
  • Client-side text search (vehicle_id, tractor_number, driver_id, driver name)
  • Metric filter (all, active, inactive, lowFuel)
  • Dispatcher filter
Determines aggregate connection status from all three data sources.Priority: error > disconnected > connecting > connected

performAPISearch

Debounced API search function for order/movement numbers.
const performAPISearch = useCallback(async (query: string) => {
  // Only search if query is alphanumeric and >= 3 chars
  if (/^[a-zA-Z0-9\-]+$/.test(query) && query.length >= 3) {
    // Call /api/movements/order/{query}
    // Extract driver_ids, vehicle_ids, trailer_ids from result
    // Set searchResultIds for filtering
  }
}, [data.vehicles]);
Important Implementation Details:
  • Debounce delay: 500ms before API call is triggered
  • Minimum query length: 3 characters
  • Valid characters: Alphanumeric and hyphens only (/^[a-zA-Z0-9\-]+$/)

API Endpoints Used

EndpointPurpose
/api/movements?limit=500Fetch movements for vehicle-to-load mapping
/api/orders/by-ids?ids={ids}Fetch customer names for order IDs (comma-separated)
/api/movements/order/{query}Search for movements by order number

Metric Filter Definitions

FilterConditionDescription
allNo filterShows all vehicles
activevehicle.driver_id existsVehicle has an assigned driver
inactivevehicle.driver_id is null/undefinedVehicle has no assigned driver
lowFuelfuel_percentage < 25Fuel level below 25%

UI Layout

┌─────────────────────────────────────────────┐
│ Header: Title + Connection Status + Export + Refresh                   │
├─────────────────────────────────────────────┤
│ KPI Cards (6 columns)                                                  │
│ [Tractor Util] [Trailer Util] [Available] [Active] [Coming] [Alerts]   │
├─────────────────────────────────────────────┤
│ Search Bar                                                             │
├─────────────────────────────────────────────┤
│ Tabs: [Dashboard] [Alerts]                                             │
├─────────────────────────────────────────────┤
│ ┌────────────────────┐ ┌───────────────────┐ │
│ │ Fleet Map (2/3 width)          │ │ Fleet Panel (1/3 width)       │ │
│ │ - View toggle: Tractors/       │ │ - Metric filter buttons       │ │
│ │   Trailers/Drivers             │ │ - Scrollable item list        │ │
│ │ - Dispatcher filter            │ │ - Item cards with status      │ │
│ │ - LiveVehicleMap or            │ │                               │ │
│ │   LiveTrailerMap               │ │                               │ │
│ └────────────────────┘ └───────────────────┘ │
└─────────────────────────────────────────────┘

LiveVehicleMap.tsx

Interactive Leaflet map component displaying real-time vehicle (tractor) locations with custom markers.

Purpose

  • Display vehicle locations on an interactive map
  • Show vehicle status via color-coded markers (moving/stopped)
  • Display detailed vehicle info in popups (driver, load, location, speed, fuel)
  • Auto-fit map bounds to show all vehicles
  • Support for filtered vehicle display

Props

interface LiveVehicleMapProps {
  backendUrl?: string;
  className?: string;
  filteredVehicles?: VehicleLocation[];
  driverIdToNameMap?: Map<string, string>;
  vehicleToLoadMap?: Map<string, VehicleActiveLoad>;
}
PropTypeDescription
backendUrlstringOverride for tracking backend URL
classNamestringAdditional CSS classes
filteredVehiclesVehicleLocation[]Vehicles to display (overrides internal data)
driverIdToNameMapMap<string, string>Driver ID to name mapping for popups
vehicleToLoadMapMap<string, VehicleActiveLoad>Vehicle to active load info for popups

Internal Hook

When filteredVehicles is not provided, the component uses useVehicleLocations() hook internally to fetch and manage vehicle data via SSE.

Default Values

SettingValueNotes
Default map center39.8283, -98.5795Geographic center of USA
Default zoom5 (with vehicles), 4 (empty)
Fit bounds padding[50, 50] pixels
Fit bounds maxZoom10Prevents zooming too close

Unit Conversions

API returns metric units. The component converts for US display:
  • Speed: API provides km/h → displayed as mph (speed * 0.621371)
  • Odometer: API provides km → displayed as miles (odometer * 0.621371)
  • Engine hours: API provides value in thousandths → divide by 1000 for actual hours

Key Functions

Validates geographic coordinates.
function isValidCoordinate(lat: number | null, lng: number | null): boolean {
  // Checks: not null, is number, not NaN, within valid ranges
  // lat: -90 to 90, lng: -180 to 180
}
Determines vehicle movement status and marker color.
StatusColorCondition
moving#10b981 (green)speed > 0 OR engine = “on”/“running”
stopped#ef4444 (red)speed = 0
unknown#3b82f6 (blue)default
Creates a Leaflet divIcon with:
  • Colored circular background based on status
  • Truck SVG icon rotated by heading
  • Pulse animation ring for moving vehicles
  • White border and shadow
Heading rotation: (heading % 360 + 360) % 360This formula normalizes any heading value (including negatives) to 0-359°. The truck SVG points north (up) by default, so heading is applied directly as CSS rotation.
Fits map bounds to show all vehicles with padding.
const handleFitToAll = useCallback(() => {
  const bounds = L.latLngBounds(
    [minLat, minLng],
    [maxLat, maxLng]
  );
  mapInstance.fitBounds(bounds, { padding: [50, 50], maxZoom: 10 });
}, [mapInstance, leafletModule, vehicleBounds]);
Vehicle popups display:
  • Vehicle header (tractor number, provider)
  • Driver name (from driverIdToNameMap)
  • Active load info (order ID, customer, destination - from vehicleToLoadMap)
  • Location (address or coordinates)
  • Speed (mph and km/h)
  • Heading (degrees)
  • Odometer (miles and km)
  • Fuel level (percentage)
  • Engine state (On/Off with runtime)
  • Last update timestamp
[Total Vehicles] [Moving (Green)] [Stopped (Red)] [Connection Status]

LiveTrailerMap.tsx

Interactive Leaflet map component displaying trailer locations with marker clustering.

Purpose

  • Display trailer locations on an interactive map
  • Cluster trailers when zoomed out for visual clarity
  • Show trailer status via color-coded markers (moving/stationary)
  • Display detailed trailer info in popups

Props

interface LiveTrailerMapProps {
  trailers: TrailerLocation[];
  className?: string;
}
PropTypeDescription
trailersTrailerLocation[]Required. Array of trailers to display
classNamestringAdditional CSS classes
Unlike LiveVehicleMap, this component does NOT fetch data internally. Trailers must be passed as a prop.

Marker Clustering

Uses leaflet.markercluster for clustering with custom configuration:
const clusterGroup = new MarkerClusterGroup({
  maxClusterRadius: 80,
  disableClusteringAtZoom: 15,
  spiderfyOnMaxZoom: true,
  showCoverageOnHover: false,
  zoomToBoundsOnClick: true,
  chunkedLoading: true,
  chunkDelay: 200,
  iconCreateFunction: // Custom cluster icon
});

Cluster Icon

Cluster icons are sized based on child count:
CountSizeFont Size
> 10050px14px
> 5040px12px
≤ 5030px10px
Color: Purple (#9333ea)

Key Functions

Default Map Center: 39.8283, -98.5795 (geographic center of USA)Safe Handling: The trailers prop defaults to an empty array if undefined is passed.
Converts trailer speed to mph.
const convertTrailerSpeed = (trailer: TrailerLocation): number | null => {
  if (trailer.speed === null) return null;
  // All providers: convert assuming km/h input
  return trailer.speed * 0.621371;
};
The current implementation converts ALL providers the same way (km/h → mph). The code has a check for Motive provider but both branches perform identical conversion.
Determines trailer movement status based on converted speed.
StatusColorCondition
moving#9333ea (purple)converted speed > 5 mph
stationary#6b7280 (gray)converted speed ≤ 5 mph or null
The 5 mph threshold prevents false “moving” readings from GPS drift when trailers are parked.
Creates a Leaflet divIcon with:
  • Colored circular background based on status
  • Package/box SVG icon rotated by heading
  • White border and shadow
Trailer popups display:
  • Trailer ID and provider
  • Location (address or coordinates)
  • Speed (mph)
  • Heading (degrees)
  • Status indicator with timestamp

Component Architecture

LiveTrailerMap
└── MapContainer
    ├── TileLayer (OpenStreetMap)
    └── MarkerClusterLayer
        └── MarkerClusterLayerInner
            └── MarkerClusterContent (manages cluster group)
The component uses a layered architecture because useMap() hook must be called within a MapContainer child component.

ConnectionStatusIndicator.tsx

A compact badge-style component showing SSE connection status with visual feedback.

Purpose

  • Display real-time SSE connection state
  • Provide visual feedback via icons and colors
  • Show error messages when connection fails

Props

interface ConnectionStatusIndicatorProps {
  connectionState: SSEConnectionState;
  lastUpdate: string | null;
}
PropTypeDescription
connectionStateSSEConnectionStateCurrent SSE connection status object
lastUpdatestring | nullISO timestamp of last data update (currently unused)

getStatusConfig

Returns icon, label, badge variant, and styling based on connection status:
StatusIconLabelColor
connectedWifi + pulse dot”Live”Green (bg-green-500)
connectingLoader2 (spinning)“Connecting”Yellow outline
disconnectedWifiOff”Disconnected”Gray (bg-gray-500)
errorAlertCircle”Error”Red (bg-red-500)

Render Output

┌─────────────────────────────────────────────┐
│  [Icon] Label     Error message (if any)                               │
│  └─ Badge ┘                                                          │
└─────────────────────────────────────────────┘
The lastUpdate prop is received but currently not displayed in the UI (prefixed with _).

ConnectionStatus.tsx

An alternative connection status component with more detailed information including cache status and reconnect functionality.

Purpose

  • Display SSE connection state with descriptive text
  • Show relative time since last update
  • Display cache hit/miss status (development only)
  • Provide reconnect button on error

Props

interface ConnectionStatusProps {
  connectionState: ConnectionState;
  lastUpdate: string | null;
  cacheStatus: 'hit' | 'miss' | null;
  onReconnect?: () => void;
}
PropTypeDescription
connectionStateConnectionStateString literal: 'connected', 'reconnecting', 'error', or other
lastUpdatestring | nullISO timestamp of last data update
cacheStatus'hit' | 'miss' | nullCache status for debugging
onReconnect() => voidCallback for reconnect button
This component uses ConnectionState from types/driver.ts, which is different from SSEConnectionState used by ConnectionStatusIndicator.

getStatusConfig

StatusColorTextPulsing
connectedGreen”Live updates active”Yes
reconnectingYellow”Connecting to live updates…”Yes
errorRed”Live updates unavailable”No
defaultGray”Disconnected”No

formatLastUpdate

Formats the timestamp as relative time:
const formatLastUpdate = () => {
  const diffSec = Math.floor((now - date) / 1000);
  
  if (diffSec < 60) return `${diffSec}s ago`;
  if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`;
  return date.toLocaleTimeString();
};

UI Elements

ElementVisibilityDescription
Status indicatorAlwaysColored dot with optional pulse animation
Status textAlwaysDescriptive connection state
”Using last known data”Error stateFallback indicator
Last update timeWhen availableRelative timestamp
Cache statusDev mode onlyShows HIT/MISS for debugging
Reconnect buttonError + callback providedManual reconnection trigger

MapLegend.tsx

A collapsible legend component explaining color codes used in fleet map markers.

Purpose

  • Explain timing status colors (on-time, early, late, critical)
  • Explain motion status indicators (moving vs idle border styles)
  • Provide visual example combining both statuses

Props

interface MapLegendProps {
  className?: string;
  defaultExpanded?: boolean;
}
PropTypeDefaultDescription
classNamestring''Additional CSS classes
defaultExpandedbooleanfalseInitial expanded state

Status Definitions

Timing Statuses

ColorLabelDescription
#10b981 (green)On-TimeArriving within scheduled window
#3b82f6 (blue)EarlyArriving 15+ minutes early
#f59e0b (amber)LateArriving 30-60 minutes late
#ef4444 (red)CriticalArriving 60+ minutes late

Motion Statuses

Border StyleBorder ColorLabelDescription
SolidWhiteMovingVehicle in motion (speed > 5mph)
DashedGray (#9ca3af)IdleVehicle stationary

Component Structure

MapLegend
├── Header (always visible)
│   ├── Info icon
│   ├── "Map Legend" title
│   └── Expand/Collapse chevron
└── Expandable Content (when expanded)
    ├── Timing Status Section
    │   └── 4 color-coded items
    ├── Motion Status Section
    │   └── 2 border-style items
    └── Example Section
        └── Combined status indicator (Late + Idle)

State Management

const [isExpanded, setIsExpanded] = useState(defaultExpanded);
The component uses a single isExpanded state to toggle visibility of the legend content.

Styling

  • Semi-transparent white background with blur (bg-white/95 backdrop-blur-sm)
  • Rounded corners with shadow and border
  • Smooth hover transition on header
  • Compact text sizing (text-xs, text-sm)