-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAvalancheForecastZoneMap.tsx
More file actions
421 lines (380 loc) · 17.7 KB
/
AvalancheForecastZoneMap.tsx
File metadata and controls
421 lines (380 loc) · 17.7 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import React, {RefObject, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import {Alert, View as RNView, StyleSheet, Text, TouchableOpacity, useWindowDimensions} from 'react-native';
import {useBottomTabBarHeight} from '@react-navigation/bottom-tabs';
import {AvalancheDangerIcon} from 'components/AvalancheDangerIcon';
import {colorFor} from 'components/AvalancheDangerTriangle';
import {incompleteQueryState, QueryState} from 'components/content/QueryState';
import {MapViewZone, mapViewZoneFor, ZoneMap} from 'components/content/ZoneMap';
import {Center, HStack, View, VStack} from 'components/core';
import {DangerScale} from 'components/DangerScale';
import {TravelAdvice} from 'components/helpers/travelAdvice';
import {AnimatedCards, AnimatedDrawerState, AnimatedMapWithDrawerController, CARD_MARGIN, CARD_WIDTH} from 'components/map/AnimatedCards';
import {AvalancheCenterSelectionModal} from 'components/modals/AvalancheCenterSelectionModal';
import {BodySm, BodySmSemibold, Title3Black} from 'components/text';
import {isAfter} from 'date-fns';
import {toDate} from 'date-fns-tz';
import {useAvalancheCenterMetadata} from 'hooks/useAvalancheCenterMetadata';
import {useMapLayerAvalancheForecasts} from 'hooks/useMapLayerAvalancheForecasts';
import {useMapLayerAvalancheWarnings} from 'hooks/useMapLayerAvalancheWarnings';
import {LoggerContext, LoggerProps} from 'loggerContext';
import {usePostHog} from 'posthog-react-native';
import {usePreferences} from 'Preferences';
import {SafeAreaView} from 'react-native-safe-area-context';
import {MainStackNavigationProps, TabNavigationProps} from 'routes';
import {AvalancheCenterID, DangerLevel, ForecastPeriod, isSupportedCenter, MapLayerFeature, ProductType} from 'types/nationalAvalancheCenter';
import {formatRequestedTime, RequestedTime, requestedTimeToUTCDate, utcDateToLocalTimeString} from 'utils/date';
import {Camera, MapState} from '@rnmapbox/maps';
import {defaultMapRegionForGeometries} from 'components/helpers/geographicCoordinates';
import {useAllMapLayers} from 'hooks/useAllMapLayers';
export interface MapProps {
center_id: AvalancheCenterID;
requestedTime: RequestedTime;
}
export const AvalancheForecastZoneMap: React.FunctionComponent<MapProps> = ({center_id, requestedTime}: MapProps) => {
const {logger} = React.useContext<LoggerProps>(LoggerContext);
const {preferences, setPreferences} = usePreferences();
const center = preferences.center;
// Fetches all the map layers in call. Unfortunately, CBAC isn't included in that call so it needs to be fetched separately
const allMapLayersResult = useAllMapLayers();
const allMapLayers = allMapLayersResult.data;
const metadataResult = useAvalancheCenterMetadata(center_id);
const metadata = metadataResult.data;
const forecastResults = useMapLayerAvalancheForecasts(center_id, requestedTime, allMapLayers, metadata);
const warningResults = useMapLayerAvalancheWarnings(center_id, requestedTime, allMapLayers);
const navigation = useNavigation<MainStackNavigationProps & TabNavigationProps>();
const [selectedZoneId, setSelectedZoneId] = useState<number | null>(null);
const topElements = React.useRef<RNView>(null);
const postHog = usePostHog();
const recordAnalytics = useCallback(() => {
if (postHog && center_id) {
postHog.screen('avalancheForecastMap', {
center: center_id,
});
}
}, [postHog, center_id]);
useFocusEffect(recordAnalytics);
const onMapPresOutsideOfPolygon = useCallback(
(_: GeoJSON.Feature) => {
// Since the polygons are layered on the map, this is only called when the map is tapped outside of a polygon
setSelectedZoneId(null);
},
[setSelectedZoneId],
);
const onPolygonPress = useCallback(
(zone: MapViewZone) => {
if (selectedZoneId === zone.zone_id) {
navigation.navigate('forecast', {
center_id: zone.center_id,
forecast_zone_id: zone.zone_id,
requestedTime: formatRequestedTime(requestedTime),
});
} else {
const selectedZoneCenter = zone.center_id;
if (isSupportedCenter(selectedZoneCenter)) {
setSelectedZoneId(zone.zone_id);
if (selectedZoneCenter !== center_id) {
setPreferences({center: selectedZoneCenter});
}
} else {
Alert.alert(`${selectedZoneCenter} is not supported`, `Please go to their website to view the full forecast for ${selectedZoneCenter} or select another center`, [
{
text: 'OK',
onPress: () => {},
},
{
text: 'Go to website',
onPress: () => {},
},
]);
}
}
},
[navigation, selectedZoneId, center_id, requestedTime, setSelectedZoneId, setPreferences],
);
const preferredCenterFeatures = useMemo(() => allMapLayers?.features.filter(feature => feature.properties.center_id === center_id), [allMapLayers, center_id]);
const avalancheCenterMapRegion = useMemo(() => defaultMapRegionForGeometries(preferredCenterFeatures?.map(feature => feature.geometry)), [preferredCenterFeatures]);
// useRef has to be used here. Animation and gesture handlers can't use props and state,
// and aren't re-evaluated on render. Fun!
const mapCameraRef = useRef<Camera>(null);
const controller = useRef<AnimatedMapWithDrawerController>(new AnimatedMapWithDrawerController(AnimatedDrawerState.Hidden, avalancheCenterMapRegion, mapCameraRef, logger));
const reanimateOnFocus = useCallback(() => {
controller.current.forceAnimateMapRegion();
}, [controller]);
useFocusEffect(reanimateOnFocus);
React.useEffect(() => {
controller.current.animateUsingUpdatedAvalancheCenterMapRegion(avalancheCenterMapRegion);
}, [avalancheCenterMapRegion, controller]);
const {width: windowWidth, height: windowHeight} = useWindowDimensions();
React.useEffect(() => {
controller.current.animateUsingUpdatedWindowDimensions(windowWidth, windowHeight);
}, [windowWidth, windowHeight, controller]);
const tabBarHeight = useBottomTabBarHeight();
React.useEffect(() => {
controller.current.animateUsingUpdatedTabBarHeight(tabBarHeight);
}, [tabBarHeight, controller]);
const onLayout = useCallback(() => {
// onLayout returns position relative to parent - we need position relative to screen
topElements.current?.measureInWindow((x, y, width, height) => {
controller.current.animateUsingUpdatedTopElementsHeight(y, height);
});
// we seem to see races between onLayout firing and the measureInWindow picking up the correct
// SafeAreaView bounds, so let's queue up another render pass in the future to hopefully converge
setTimeout(() => {
if (topElements.current) {
topElements.current.measureInWindow((x, y, width, height) => {
controller.current.animateUsingUpdatedTopElementsHeight(y, height);
});
}
}, 50);
}, [controller]);
const onSelectCenter = useCallback(
(center: AvalancheCenterID) => {
setPreferences({center: center, hasSeenCenterPicker: true});
},
[setPreferences],
);
const onCameraChanged = useCallback(
(mapState: MapState) => {
if (mapState.gestures.isGestureActive) {
if (mapState.properties.zoom < 5.5 && controller.current.state !== AnimatedDrawerState.Hidden) {
controller.current.setState(AnimatedDrawerState.Hidden, false);
setSelectedZoneId(null);
}
}
},
[controller, setSelectedZoneId],
);
// default to the values in the map layer, but update it with the forecasts and warnings we've fetched
const zonesById = useMemo(() => {
return allMapLayers?.features.reduce((accum: Record<string, MapViewZone>, feature: MapLayerFeature) => {
accum[feature.id] = mapViewZoneFor(feature);
return accum;
}, {});
}, [allMapLayers]);
useEffect(() => {
forecastResults
.map(result => result.data) // get data from the results
.filter(data => data) // only operate on results that have succeeded
.forEach(forecast => {
if (forecast && forecast.forecast_zone && zonesById) {
forecast.forecast_zone.forEach(({id}) => {
if (zonesById[id]) {
// If the zone is marked as off-season in the map layer, we want the danger level to be None so that the color is grey
// regarless of what the forecast says
if (zonesById[id].feature.properties.off_season) {
zonesById[id].danger_level = DangerLevel.None;
} else {
// the map layer will expose old forecasts with their danger level as appropriate, but the map expects to show a card
// that doesn't divulge the old forecast's rating, travel advice or publication/expiry times, so we clear things out
if (
!zonesById[id].end_date ||
(zonesById[id].end_date &&
isAfter(requestedTimeToUTCDate(requestedTime), toDate(new Date(zonesById[id].end_date || '2000-01-01'), {timeZone: 'UTC'}))) /* requesting after expiry */
) {
zonesById[id].danger_level = DangerLevel.GeneralInformation;
zonesById[id].end_date = null;
zonesById[id].start_date = null;
}
// product-specific queries can give us results that are expired or older than the map layer, in which case we don't
// want to use them
if (
(forecast.product_type === ProductType.Forecast || forecast.product_type === ProductType.Summary) &&
forecast.expires_time &&
(isAfter(toDate(new Date(forecast.expires_time), {timeZone: 'UTC'}), requestedTimeToUTCDate(requestedTime)) /* product is not expired */ ||
(zonesById[id].end_date &&
isAfter(
toDate(new Date(forecast.expires_time), {timeZone: 'UTC'}),
toDate(new Date(zonesById[id].end_date || '2000-01-01'), {timeZone: 'UTC'}),
))) /* product newer than map layer */
) {
if (forecast.product_type === ProductType.Forecast) {
const currentDanger = forecast.danger.find(d => d.valid_day === ForecastPeriod.Current);
if (currentDanger) {
const maxCurrentDanger = Math.max(currentDanger.lower, currentDanger.middle, currentDanger.upper) as DangerLevel;
// If we're in season, use the forecast's danger level only if it's not None
if (maxCurrentDanger !== DangerLevel.None) {
zonesById[id].danger_level = maxCurrentDanger;
}
}
}
// Regardless if the product type is a summary or forecast, we want to use the forecast API timestamp as it has timezone information
zonesById[id].start_date = forecast.published_time;
zonesById[id].end_date = forecast.expires_time;
}
}
}
});
}
});
}, [zonesById, forecastResults, requestedTime]);
useEffect(() => {
warningResults
.map(result => result.data) // get data from the results
.forEach(warning => {
if (!warning || !zonesById) {
return;
}
// the warnings endpoint can return warnings, watches and special bulletins; we only want to make the map flash
// when there's an active warning for the zone
if (
'product_type' in warning.data &&
warning.data.product_type === ProductType.Warning &&
'expires_time' in warning.data &&
isAfter(toDate(new Date(warning.data.expires_time), {timeZone: 'UTC'}), requestedTimeToUTCDate(requestedTime))
) {
const mapViewZoneData = zonesById[warning.zone_id];
if (mapViewZoneData) {
mapViewZoneData.hasWarning = true;
}
}
});
}, [zonesById, warningResults, requestedTime]);
const zones = useMemo(() => (zonesById !== undefined ? Object.keys(zonesById).map(k => zonesById[k]) : []), [zonesById]);
const selectedACZones = useMemo(() => zones.filter(zone => zone.feature.properties.center_id === center_id), [zones, center_id]);
const showAvalancheCenterSelectionModal = useMemo(() => !preferences.hasSeenCenterPicker, [preferences.hasSeenCenterPicker]);
if (incompleteQueryState(allMapLayersResult, metadataResult, ...forecastResults, ...warningResults) || !allMapLayers || !metadata || !preferredCenterFeatures) {
return (
<SafeAreaView edges={['top', 'left', 'right']}>
<Center width="100%" height="100%">
<QueryState
results={[allMapLayersResult, metadataResult, ...forecastResults, ...warningResults]}
terminal
customMessage={{
notFound: () => ({
headline: 'Missing forecast',
body: 'There may not be a forecast available for today.',
}),
}}
/>
</Center>
</SafeAreaView>
);
}
return (
<>
<ZoneMap
ref={mapCameraRef}
style={StyleSheet.absoluteFillObject}
initialCameraBounds={avalancheCenterMapRegion.cameraBounds}
zones={zones}
selectedZoneId={selectedZoneId}
onPolygonPress={onPolygonPress}
onMapPress={onMapPresOutsideOfPolygon}
onCameraChanged={onCameraChanged}
/>
<VStack ref={topElements} width="100%" position="absolute" left={0} right={0} mt={8} px={4} flex={1} onLayout={onLayout}>
<DangerScale width="100%" />
</VStack>
<AvalancheForecastZoneCards
key={`${center}-zoneCards`}
center_id={center}
date={requestedTime}
zones={selectedACZones}
selectedZoneId={selectedZoneId}
setSelectedZoneId={setSelectedZoneId}
controllerRef={controller}
/>
<AvalancheCenterSelectionModal visible={showAvalancheCenterSelectionModal} initialSelection={preferences.center} onClose={onSelectCenter} />
</>
);
};
const AvalancheForecastZoneCards: React.FunctionComponent<{
center_id: AvalancheCenterID;
date: RequestedTime;
zones: MapViewZone[];
selectedZoneId: number | null;
setSelectedZoneId: React.Dispatch<React.SetStateAction<number | null>>;
controllerRef: RefObject<AnimatedMapWithDrawerController>;
}> = ({center_id, date, zones, selectedZoneId, setSelectedZoneId, controllerRef}) => {
return AnimatedCards<MapViewZone, number>({
center_id: center_id,
date: date,
items: zones,
getItemId: zone => zone.zone_id,
selectedItemId: selectedZoneId,
setSelectedItemId: setSelectedZoneId,
controllerRef: controllerRef,
renderItem: ({date, item}) => <AvalancheForecastZoneCard date={date} zone={item} />,
});
};
const AvalancheForecastZoneCard: React.FunctionComponent<{
date: RequestedTime;
zone: MapViewZone;
}> = React.memo(({date, zone}: {date: RequestedTime; zone: MapViewZone}) => {
const {width} = useWindowDimensions();
const navigation = useNavigation<MainStackNavigationProps>();
const dangerLevel = zone.danger_level ?? DangerLevel.None;
const dangerColor = colorFor(dangerLevel);
const onPress = useCallback(() => {
navigation.navigate('forecast', {
center_id: zone.center_id,
forecast_zone_id: zone.zone_id,
requestedTime: formatRequestedTime(date),
});
}, [navigation, zone, date]);
return (
<TouchableOpacity activeOpacity={0.9} onPress={onPress}>
<VStack borderRadius={8} bg="white" width={width * CARD_WIDTH} mx={CARD_MARGIN * width} height={'100%'}>
<View height={8} width="100%" bg={dangerColor.string()} borderTopLeftRadius={8} borderTopRightRadius={8} pb={0} />
<VStack px={24} pt={4} pb={12} space={8}>
<HStack space={8} alignItems="center">
<AvalancheDangerIcon style={{height: 32}} level={dangerLevel} />
<DangerLevelTitle dangerLevel={dangerLevel} />
</HStack>
<Title3Black>{zone.name}</Title3Black>
{(zone.start_date || zone.start_date) && (
<VStack py={8}>
<Text>
{zone.start_date && (
<>
<BodySm>Published: </BodySm>
<BodySm>{utcDateToLocalTimeString(zone.start_date)}</BodySm>
{'\n'}
</>
)}
{zone.end_date && (
<>
<BodySm>Expires: </BodySm>
<BodySm>{utcDateToLocalTimeString(zone.end_date)}</BodySm>
</>
)}
</Text>
</VStack>
)}
<Text>
<BodySm>Travel advice: </BodySm>
<TravelAdvice dangerLevel={dangerLevel} HeadingText={BodySm} BodyText={BodySm} />
</Text>
</VStack>
</VStack>
</TouchableOpacity>
);
});
AvalancheForecastZoneCard.displayName = 'AvalancheForecastZoneCard';
const DangerLevelTitle: React.FunctionComponent<{
dangerLevel: DangerLevel;
}> = ({dangerLevel}) => {
switch (dangerLevel) {
case DangerLevel.GeneralInformation:
case DangerLevel.None:
return (
<BodySmSemibold>
<Text style={{textTransform: 'capitalize'}}>No Rating</Text>
</BodySmSemibold>
);
case DangerLevel.Low:
case DangerLevel.Moderate:
case DangerLevel.Considerable:
case DangerLevel.High:
case DangerLevel.Extreme:
return (
<BodySmSemibold>
{dangerLevel} - <Text style={{textTransform: 'capitalize'}}>{DangerLevel[dangerLevel]}</Text>
</BodySmSemibold>
);
}
const invalid: never = dangerLevel;
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unknown danger level: ${invalid}`);
};