File size: 7,640 Bytes
4851501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Frontend Component Architecture

Overview of GeoQuery's React components and their interactions.

---

## Component Hierarchy

```
App (Next.js Layout)
└── Main Page
    β”œβ”€β”€ ChatPanel
    β”‚   β”œβ”€β”€ MessageList
    β”‚   β”œβ”€β”€ InputForm
    β”‚   └── CitationLinks
    β”œβ”€β”€ MapViewer
    β”‚   β”œβ”€β”€ LeafletMap
    β”‚   β”œβ”€β”€ LayerControl
    β”‚   β”‚   β”œβ”€β”€ SortableLayerItem (draggable)
    β”‚   β”‚   └── LayerSettings
    β”‚   └── EmptyState
    └── DataExplorer
        β”œβ”€β”€ ResultsTable
        └── ExportButton
```

---

## Core Components

### ChatPanel (`components/ChatPanel.tsx`)

Main conversational interface with streaming support.

**Props**:
```typescript
interface ChatPanelProps {
  onLayerAdd: (layer: MapLayer) => void;
}
```

**State**:
```typescript
const [messages, setMessages] = useState<Message[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [currentThought, setCurrentThought] = useState<string>('');
```

**Key Features**:
- SSE (Server-Sent Events) for streaming
- Real-time thought process display
- Markdown rendering
- Citation link generation
- Layer reference chips

**SSE Implementation**:
```typescript
const response = await fetch('/api/chat', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({message, history})
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const {value, done} = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  // Process SSE events...
}
```

**Event Handling**:
- `status`: Updates loading status
- `intent`: Shows detected intent
- `chunk`: Streams text incrementally
- `result`: Adds map layer and displays data

---

### MapViewer (`components/MapViewer.tsx`)

Interactive Leaflet map with layer management.

**Props**:
```typescript
interface MapViewerProps {
  layers: MapLayer[];
  onLayerUpdate: (id: string, updates: Partial<MapLayer>) => void;
  onLayerRemove: (id: string) => void;
  onLayerReorder: (fromIndex: number, toIndex: number) => void;
}
```

**Layer Model**:
```typescript
interface MapLayer {
  id: string;
  name: string;
  data: GeoJSON.FeatureCollection;
  visible: boolean;
  style: {
    color: string;
    fillColor: string;
    fillOpacity: number;
    weight: number;
  };
  choropleth?: {
    enabled: boolean;
    column: string;
    palette: string;
    scale: 'linear' | 'log';
    min?: number;
    max?: number;
  };
  pointMarker?: {
    icon: string;
    style: 'icon' | 'circle';
    color: string;
    size: number;
  };
}
```

**Key Features:**
- Layer visibility toggle
- Style customization (color, opacity, weight)
- Drag-and-drop layer reordering
- Auto-fit bounds to new layers
- Choropleth visualization
- Point rendering modes (icon vs circle)

**Point Rendering Logic**:
```typescript
const pointToLayer = (feature: any, latlng: L.LatLng) => {
  if (layer.pointMarker?.style === "circle") {
    // Simple circle for large datasets
    return L.circleMarker(latlng, {
      radius: 5,
      fillColor: layer.pointMarker.color,
      color: '#ffffff',
      weight: 2,
      opacity: 1,
      fillOpacity: 0.7
    });
  }
  
  // Emoji icon for POI
  return L.marker(latlng, {
    icon: L.divIcon({
      html: `<div style="font-size: 32px">${layer.pointMarker.icon}</div>`,
      className: 'custom-emoji-marker',
      iconSize: [32, 32]
    })
  });
};
```

**Choropleth Implementation**:
```typescript
// Calculate color based on value
const fillColor = getChoroplethColor(
  feature.properties[choropleth.column],
  choropleth.min,
  choropleth.max,
  choropleth.palette,
  choropleth.scale
);
```

---

### DataExplorer (`components/DataExplorer.tsx`)

Tabular data view with export capabilities.

**Props**:
```typescript
interface DataExplorerProps {
  data: any[];
  visible: boolean;
}
```

**Features**:
- Responsive table
- Column sorting
- CSV export
- Pagination for large datasets

---

## Sub-Components

### SortableLayerItem

Draggable layer control item using `@dnd-kit`.

**Features**:
- Drag handle with visual feedback
- Layer visibility toggle
- Settings expansion
- Style controls (color pickers, sliders)
- Remove layer button

**Drag-and-Drop**:
```typescript
const {
  attributes,
  listeners,
  setNodeRef,
  transform,
  transition
} = useSortable({ id: layer.id });

const style = {
  transform: CSS.Transform.toString(transform),
  transition
};
```

### AutoFitBounds

Utility component that auto-zooms map to new layers.

```typescript
function AutoFitBounds({ layers }: { layers: MapLayer[] }) {
  const map = useMap();
  
  useEffect(() => {
    if (layers.length > prevLayersLength.current) {
      const latestLayer = layers[layers.length - 1];
      const bounds = L.geoJSON(latestLayer.data).getBounds();
      if (bounds.isValid()) {
        map.fitBounds(bounds, { padding: [50, 50] });
      }
    }
  }, [layers]);
  
  return null;
}
```

---

## State Management

### Global State (Main Page)

```typescript
const [layers, setLayers] = useState<MapLayer[]>([]);

const handleLayerAdd = (geojson: GeoJSON.FeatureCollection) => {
  const newLayer: MapLayer = {
    id: geojson.properties.layer_id,
    name: geojson.properties.layer_name,
    data: geojson,
    visible: true,
    style: geojson.properties.style,
    choropleth: geojson.properties.choropleth,
    pointMarker: geojson.properties.pointMarker
  };
  
  setLayers(prev => [...prev, newLayer]);
};
```

### Layer Updates

```typescript
const handleLayerUpdate = (id: string, updates: Partial<MapLayer>) => {
  setLayers(prev => prev.map(layer =>
    layer.id === id ? { ...layer, ...updates } : layer
  ));
};
```

---

## Styling & Theming

### Global Styles (`app/globals.css`)

- Tailwind CSS for utility-first styling
- Custom CSS variables for theming
- Leaflet overrides for custom markers

### Color Palettes

```typescript
const COLOR_PALETTES = {
  viridis: ['#440154', '#482878', ... '#fde725'],
  blues: ['#f7fbff', ... '#08306b'],
  reds: ['#fff5f0', ... '#67000d']
};
```

---

## Performance Optimizations

### React Optimizations

1. **Memoization**:
   ```typescript
   const MemoizedGeoJSON = React.memo(GeoJSON);
   ```

2. **Key Management**:
   ```typescript
   key={layer.id + JSON.stringify(layer.style)}
   ```

3. **Lazy Loading**:
   - Components loaded on-demand
   - Map tiles loaded progressively

### Leaflet Optimizations

1. **Circle Markers for Large Datasets**:
   - Use `L.circleMarker` instead of `L.divIcon` for >500 points
   - Significantly faster rendering

2. **Layer Virtualization**:
   - Only render visible layers
   - Remove offscreen features

---

## Responsive Design

### Breakpoints

- **Mobile** (<640px): Stacked layout
- **Tablet** (640-1024px): Sidebar collapses
- **Desktop** (>1024px): Full sidebar

### Mobile Adaptations

- Layer legend becomes bottom sheet
- Map controls repositioned
- Touch-friendly drag handles

---

## Accessibility

- **Keyboard Navigation**: Tab through controls
- **Screen Readers**: ARIA labels on interactive elements
- **Color Contrast**: WCAG AA compliant
- **Focus Indicators**: Visible focus states

---

## Icons & Assets

- **Lucide React**: Icon library for UI elements
- **Leaflet Markers**: Default and custom markers
- **Emoji Icons**: Unicode emojis for POI markers

---

## Next Steps

- **Backend Services**: [../backend/CORE_SERVICES.md](../backend/CORE_SERVICES.md)
- **API Reference**: [../backend/API_ENDPOINTS.md](../backend/API_ENDPOINTS.md)
- **Data Flow**: [../DATA_FLOW.md](../DATA_FLOW.md)