File size: 8,147 Bytes
6ef6359
87dbbc6
6ef6359
 
 
 
74460ff
e1e9687
5086de6
 
 
 
 
08b99b2
5086de6
 
 
 
 
 
 
 
 
6ef6359
 
5086de6
08b99b2
6ef6359
5086de6
d936242
08b99b2
 
 
 
 
 
 
 
 
 
e1e9687
08b99b2
 
 
 
e1e9687
 
 
 
 
 
6ef6359
 
87dbbc6
 
 
 
 
 
 
 
 
 
 
 
08b99b2
 
 
 
 
 
 
87dbbc6
08b99b2
 
 
 
 
 
 
87dbbc6
 
08b99b2
87dbbc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ef6359
08b99b2
5086de6
 
 
 
 
 
 
 
 
 
 
08b99b2
 
 
 
 
b209d78
08b99b2
5086de6
 
 
6ef6359
5086de6
6ef6359
5086de6
6ef6359
5086de6
 
 
 
6ef6359
 
5086de6
6ef6359
5086de6
6ef6359
 
 
08b99b2
 
 
 
 
 
 
 
 
 
 
 
5086de6
6ef6359
 
 
 
 
 
 
5086de6
6ef6359
 
 
 
 
74460ff
bc3a44a
87dbbc6
 
5086de6
08b99b2
 
 
 
87dbbc6
08b99b2
 
 
74460ff
08b99b2
 
 
74460ff
 
08b99b2
 
e1e9687
 
08b99b2
 
74460ff
 
 
 
 
08b99b2
 
74460ff
08b99b2
74460ff
 
 
08b99b2
 
 
 
 
 
 
 
74460ff
08b99b2
 
74460ff
 
 
 
08b99b2
74460ff
08b99b2
 
d936242
6ef6359
5086de6
e1e9687
 
 
 
 
 
 
 
 
 
 
 
 
 
5086de6
08b99b2
6ef6359
 
5086de6
 
6ef6359
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import React, { useState, useEffect, useRef } from 'react';
import { DEFAULT_CENTER } from './utils/geo';
import RadarMap from './components/RadarMap';
import FlightRoster from './components/FlightRoster';
import DevConsole from './components/DevConsole';
import FlightModal from './components/FlightModal';
import AdminPanel from './components/AdminPanel';
import RouteSidebar from './components/RouteSidebar';
import './App.css';

const INITIAL_STATE = {
  simulation_time: 0,
  is_terminal: false,
  active_runways: [],
  wind_heading: 0,
  wind_speed: 0,
  time_scale: 1,
  aircrafts: {},
  events: [],
  airspace: { nodes: [], edges: [] },
  airports: [],
  config: null
};

function App() {
  const [data, setData] = useState(INITIAL_STATE);
  const [logs, setLogs] = useState([]);
  const [selectedFlight, setSelectedFlight] = useState(null);
  const [activeAirport, setActiveAirport] = useState({ ...DEFAULT_CENTER, name: "Loading..." });
  const [hoveredWaypoint, setHoveredWaypoint] = useState(null);
  
  // Drafting States (Unified)
  const [draftingMode, setDraftingMode] = useState(null); // null | 'airport' | 'runway' | 'waypoint' | 'route'
  const [airportName, setAirportName] = useState("");
  const [runwayPoints, setRunwayPoints] = useState([]);
  const [mousePos, setMousePos] = useState(null);
  const [isRunwayBidirectional, setIsRunwayBidirectional] = useState(true);
  
  // STAR Builder specific state
  const [starDraft, setStarDraft] = useState({
    name: '',
    gate: 'N',
    runway_id: null,
    sequence: [] // List of Waypoint IDs
  });
  const [sidDraft, setSidDraft] = useState({
    name: '',
    runway_id: null,
    gate: 'N',
    sequence: []
  });
  const wsRef = useRef(null);

  const sendWSMessage = (type, payload) => {
    // 1. Optimistic/Local Update for Development
    if (type === 'create_airport') {
      setData(prev => ({
        ...prev,
        airports: [...(prev.airports || []), { ...payload, name: payload.name || `Airport ${prev.airports.length + 1}`, runways: [] }]
      }));
    }

    if (type === 'create_runway') {
      setData(prev => {
        const airports = (prev.airports || []).map(ap => {
          if (ap.airport_code === payload.airport_code) {
            const rwys = [{ 
              id: payload.runway_id || `RWY_${(ap.runways || []).length + 1}`, 
              heading: payload.heading || 0,
              start: payload.start, 
              end: payload.end 
            }];
            if (payload.bidirectional) {
              const rw_id = payload.runway_id || `RWY_${(ap.runways || []).length + 1}`;
              rwys.push({ 
                id: `${rw_id}_REV`, 
                heading: (payload.heading || 0 + 180) % 360,
                start: payload.end, 
                end: payload.start 
              });
            }
            const updated = { ...ap, runways: [...(ap.runways || []), ...rwys] };
            if (activeAirport?.airport_code === ap.airport_code) {
              setActiveAirport(updated);
            }
            return updated;
          }
          return ap;
        });
        return { ...prev, airports };
      });
    }

    // 2. Network Send
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({ type, payload }));
    }
  };

  useEffect(() => {
    // 1. Real-time: Connect to WebSocket with Auto-Reconnect
    const connectWS = () => {
      const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws';
      const ws = new WebSocket(wsUrl);
      wsRef.current = ws;

      ws.onopen = () => console.log('✅ Connected to RL Backend');

      ws.onmessage = (event) => {
        try {
          const incomingData = JSON.parse(event.data);
          if (incomingData && typeof incomingData === 'object') {
            // 1. Update Simulation State
            setData(prevData => ({ ...prevData, ...incomingData }));
            
            // 2. Accumulate Logs (Independent State)
            if (incomingData.events && incomingData.events.length > 0) {
              setLogs(prevLogs => [...prevLogs, ...incomingData.events].slice(-500));
            }
          }
        } catch (err) {
          console.error("❌ WS Message Error:", err);
        }
      };

      ws.onerror = (error) => console.error('⚠️ WebSocket Error:', error);

      ws.onclose = (e) => {
        console.log(`🔌 Disconnected (Code: ${e.code}). Retrying in 2s...`);
        setTimeout(connectWS, 2000);
      };
    };

    connectWS();
    return () => {
      if (wsRef.current) wsRef.current.close();
    };
  }, []);

  // Update active airport when airports list changes
  useEffect(() => {
    if (data.airports && data.airports.length > 0) {
      setActiveAirport(prevActive => {
        if (!prevActive || prevActive.name === "Loading...") {
          return data.airports[0];
        }
        return data.airports.find(a => a.name === prevActive.name) || data.airports[0];
      });
    }
  }, [data.airports]);

  const handleFlightSelect = (flight) => setSelectedFlight(flight);

  const handleSendCommand = (cmd) => {
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({ type: 'command', payload: cmd }));
    }
  };

  const handleCloseModal = () => setSelectedFlight(null);

  const flightsList = data.aircrafts ? Object.values(data.aircrafts) : [];

  return (
    <div className="dashboard-container">
      <AdminPanel
        gameState={data}
        airports={data.airports || []}
        activeAirport={activeAirport}
        activeAirportConfig={data.config}
        onSelectAirport={(ap) => {
          setActiveAirport(ap);
          sendWSMessage('select_airport', { code: ap.airport_code });
        }}
        sendWSMessage={sendWSMessage}
        
        draftingMode={draftingMode}
        setDraftingMode={setDraftingMode}

        airportName={airportName}
        setAirportName={setAirportName}
        isRunwayBidirectional={isRunwayBidirectional}
        setIsRunwayBidirectional={setIsRunwayBidirectional}

        starDraft={starDraft}
        setStarDraft={setStarDraft}
        sidDraft={sidDraft}
        setSidDraft={setSidDraft}
      />

      <RadarMap
        flights={flightsList}
        selectedFlight={selectedFlight}
        onSelectFlight={handleFlightSelect}
        airspace={data.airspace || { nodes: [], edges: [] }}
        airports={data.airports || []}
        activeAirport={activeAirport}
        setActiveAirport={setActiveAirport}
        activeAirportConfig={data.config}
        activeRunways={data.active_runways || []}
        windHeading={data.wind_heading || 0}
        windSpeed={data.wind_speed || 0}
        onSelectAirport={(ap) => {
          setActiveAirport(ap);
          sendWSMessage('select_airport', { code: ap.airport_code });
        }}
        sendWSMessage={sendWSMessage}
        
        draftingMode={draftingMode}
        setDraftingMode={setDraftingMode}
        
        airportName={airportName}
        setAirportName={setAirportName}
        runwayPoints={runwayPoints}
        setRunwayPoints={setRunwayPoints}
        mousePos={mousePos}
        setMousePos={setMousePos}
        isRunwayBidirectional={isRunwayBidirectional}
        
        starDraft={starDraft}
        setStarDraft={setStarDraft}
        setHoveredWaypoint={setHoveredWaypoint}
      />

      <div className="sidebar-panel">
        <div className="sidebar-roster-section">
          <FlightRoster
            gameState={data}
            flights={flightsList}
            onSelectFlight={handleFlightSelect}
            sendWSMessage={sendWSMessage}
            hoveredWaypoint={hoveredWaypoint}
          />
        </div>
        <div className="sidebar-routes-section">
          <RouteSidebar gameState={data} />
        </div>
      </div>

      <DevConsole actions={logs} onSendCommand={handleSendCommand} />

      {/* Renders over everything when a flight is selected */}
      <FlightModal
        flight={selectedFlight}
        onClose={handleCloseModal}
      />
    </div>
  );
}

export default App;