-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathGlobalFrame.js
More file actions
468 lines (426 loc) · 18.6 KB
/
Copy pathGlobalFrame.js
File metadata and controls
468 lines (426 loc) · 18.6 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import React, { useContext, useEffect, useState } from 'react';
import { Alert, Box, Button, Dialog, Snackbar } from '@mui/material';
import OsmAndMap from '../map/OsmAndMap';
import MainMenu from '../menu/MainMenu';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import AppContext, { TRAVEL_ROUTE_ID_PARAM } from '../context/AppContext';
import GeneralPanelButtons from './panelbuttons/GeneralPanelButtons';
import { GlobalConfirmationDialog } from '../dialogs/GlobalConfirmationDialog';
import HeaderMenu from './components/header/HeaderMenu';
import {
HEADER_SIZE,
MAIN_MENU_MIN_SIZE,
MAIN_MENU_OPEN_SIZE,
MAIN_PAGE_TYPE,
MAIN_URL_WITH_SLASH,
MENU_INFO_CLOSE_SIZE,
MENU_INFO_OPEN_SIZE,
POI_URL,
STOP_URL,
isTravelPath,
liveHash,
} from '../manager/GlobalManager';
import { useWindowSize } from '../util/hooks/useWindowSize';
import GlobalAlert from './components/GlobalAlert';
import LiveShareRequests from './components/LiveShareRequests';
import DialogTitle from '@mui/material/DialogTitle';
import dialogStyles from '../dialogs/dialog.module.css';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import isEmpty from 'lodash-es/isEmpty';
import { createTrackGroups, getGpxFiles, filterSmartFolders, TRACK_VISIBLE_FLAG } from '../manager/track/TracksManager';
import { addCloseTracksToRecently, VISIBLE_SHARE_MARKER } from '../menu/visibletracks/VisibleTracks';
import PhotosModal from '../menu/search/explore/PhotosModal';
import InstallBanner from './components/InstallBanner';
import { hideAllTracks } from '../manager/track/DeleteTrackManager';
import GlobalGraph from '../graph/mapGraph/GlobalGraph';
import LoginContext from '../context/LoginContext';
import { poiUrlParams } from '../manager/PoiManager';
import { createUrlParams } from '../util/Utils';
const ENCODED_COMMA = '%2C';
const ENCODED_COLON = '%3A';
const ENCODED_SEMICOLON = '%3B';
const GlobalFrame = () => {
const ctx = useContext(AppContext);
const ltx = useContext(LoginContext);
const [showInfoBlock, setShowInfoBlock] = useState(false);
const [clearState, setClearState] = useState(false);
const [openMainMenu, setOpenMainMenu] = useState(false);
const [openErrorDialog, setOpenErrorDialog] = useState(false);
const [menuInfo, setMenuInfo] = useState(null);
const [width, height] = useWindowSize();
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
const [showInstallBanner, setShowInstallBanner] = useState(false);
const MAIN_MENU_SIZE = openMainMenu ? `${MAIN_MENU_OPEN_SIZE}px` : `${MAIN_MENU_MIN_SIZE}px`;
const MENU_INFO_SIZE =
menuInfo || ltx.openLoginMenu || ctx.infoBlockWidth === `${MENU_INFO_OPEN_SIZE}px`
? `${MENU_INFO_OPEN_SIZE}px`
: `${MENU_INFO_CLOSE_SIZE}px`;
const NAVIGATION_SETTINGS_WIDTH = ctx.openNavigationSettings ? MENU_INFO_OPEN_SIZE : 0;
const TRANSPORT_ROUTE_DETAILS_WIDTH =
ctx.selectedTransportRoute && !ctx.selectedTransportRoute.isPreview ? MENU_INFO_OPEN_SIZE : 0;
const TOTAL_MENU_INFO_WIDTH =
Number(MENU_INFO_SIZE.replace('px', '')) + NAVIGATION_SETTINGS_WIDTH + TRANSPORT_ROUTE_DETAILS_WIDTH;
// check configure map state
useEffect(() => {
if (!ctx.configureMapState.showTracks) {
hideAllTracks(ctx);
}
}, [ctx.configureMapState]);
useEffect(() => {
if (menuInfo) {
ctx.setInfoBlockWidth(`${MENU_INFO_OPEN_SIZE}px`);
}
}, [menuInfo]);
useEffect(() => {
const userAgent = window.navigator.userAgent.toLowerCase();
const mobileDeviceRegex = /android|iphone|ipad|ipod/i;
const isMobileDevice = mobileDeviceRegex.test(userAgent);
const isIOS = /iphone|ipad|ipod/.test(userAgent);
const isSafari = isIOS && /safari/.test(userAgent) && !/crios|fxios|edgios|opios/.test(userAgent);
setShowInstallBanner(isMobileDevice && !isSafari);
}, [height, width]);
// URL normalization
useEffect(() => {
const currentSearch = location.search;
if (!currentSearch) return;
const hasEncodedChars =
currentSearch.includes(ENCODED_COMMA) ||
currentSearch.includes(ENCODED_COLON) ||
currentSearch.includes(ENCODED_SEMICOLON);
if (!hasEncodedChars) return;
const searchParams = new URLSearchParams(currentSearch);
const params = {};
searchParams.forEach((value, key) => {
params[key] = value;
});
const normalizedSearch = createUrlParams(params);
if (normalizedSearch !== currentSearch) {
const newUrl = location.pathname + normalizedSearch + liveHash();
window.history.replaceState(window.history.state, '', newUrl);
}
}, [location.search]);
// remove garmin param from url after processing it in GarminConnectManager
useEffect(() => {
const params = new URLSearchParams(globalThis.location.search);
if (!params.has('garmin')) {
return;
}
params.delete('garmin');
const qs = params.toString();
const newUrl = location.pathname + (qs ? `?${qs}` : '') + (globalThis.location.hash || '');
globalThis.history.replaceState(globalThis.history.state, '', newUrl);
}, [location.search, location.pathname]);
useEffect(() => {
if (ctx.infoBlockWidth === `${MENU_INFO_CLOSE_SIZE}px`) {
setShowInfoBlock(false);
if (menuInfo !== null) {
setMenuInfo(null);
}
if (location.pathname !== MAIN_URL_WITH_SLASH) {
if (ctx.pageParams[MAIN_PAGE_TYPE] !== undefined) {
navigate(MAIN_URL_WITH_SLASH + ctx.pageParams[MAIN_PAGE_TYPE] + liveHash());
} else {
navigate(MAIN_URL_WITH_SLASH + liveHash());
}
}
}
}, [ctx.infoBlockWidth]);
useEffect(() => {
setOpenErrorDialog(!!ctx.trackErrorMsg);
}, [ctx.trackErrorMsg]);
// add new files to visible tracks
useEffect(() => {
if (!isEmpty(ctx.gpxFiles)) {
let savedVisible = JSON.parse(localStorage.getItem(TRACK_VISIBLE_FLAG));
const { newVisFiles, newVisFilesNames } = processTracks(ctx.gpxFiles, savedVisible);
mergeVisibleTracks(savedVisible, newVisFiles, newVisFilesNames, false);
} else {
if (isEmpty(ctx.shareWithMeFiles?.tracks)) {
let newVisFiles = {
old: [],
new: [],
};
ctx.setVisibleTracks({ ...newVisFiles });
}
}
}, [ctx.gpxFiles]);
useEffect(() => {
if (!isEmpty(ctx.shareWithMeFiles?.tracks)) {
let savedVisible = JSON.parse(localStorage.getItem(TRACK_VISIBLE_FLAG));
const { newVisFiles, newVisFilesNames } = processTracks(
ctx.shareWithMeFiles.tracks,
savedVisible,
VISIBLE_SHARE_MARKER
);
mergeVisibleTracks(savedVisible, newVisFiles, newVisFilesNames, true);
} else {
if (isEmpty(ctx.gpxFiles)) {
let newVisFiles = {
old: [],
new: [],
};
ctx.setVisibleTracks({ ...newVisFiles });
}
}
}, [ctx.shareWithMeFiles]);
useEffect(() => {
if (location.pathname.includes(POI_URL) && (!ctx.selectedWptId || ctx.selectedWptId?.id === -1)) {
ctx.setProcessingPoiByUrl(true);
const params = {};
Object.keys(poiUrlParams).forEach((key) => {
params[key] = searchParams.get(poiUrlParams[key]);
});
ctx.setPoiByUrl((prev) => {
return {
...prev,
params,
};
});
} else {
ctx.setProcessingPoiByUrl(false);
ctx.setPoiByUrl((prev) => {
return prev ? { ...prev, open: false } : prev;
});
}
}, [location.pathname]);
useEffect(() => {
if (location.pathname.includes(STOP_URL)) {
ctx.setProcessingStopByUrl(true);
ctx.setStopByUrl((prev) => {
return {
...prev,
params: {
id: searchParams.get('id'),
pin: searchParams.get('pin'),
},
};
});
} else {
ctx.setProcessingStopByUrl(false);
ctx.setStopByUrl((prev) => {
return prev ? { ...prev, open: false } : prev;
});
}
}, [location.pathname]);
useEffect(() => {
const routeId = searchParams.get(TRAVEL_ROUTE_ID_PARAM);
if (isTravelPath(location.pathname)) {
if (routeId) {
ctx.setTravelRouteIdByUrl(routeId);
ctx.setProcessingTravelRouteByUrl(true);
setShowInfoBlock(true);
ctx.setInfoBlockWidth(MENU_INFO_OPEN_SIZE + 'px');
} else {
ctx.setTravelRouteIdByUrl(null);
ctx.setProcessingTravelRouteByUrl(false);
}
}
}, [location.pathname, location.search]);
function mergeVisibleTracks(savedVisible, newVisFiles, newVisFilesNames, shared) {
savedVisible = savedVisible ?? { old: [], new: [], open: [] };
const filterCondition = (name) =>
shared ? !name.startsWith(VISIBLE_SHARE_MARKER) : name.startsWith(VISIBLE_SHARE_MARKER);
// get other track names and add them to the visible tracks with the same order
const otherTrackNames = {
old: savedVisible.old.filter(filterCondition),
new: savedVisible.new.filter(filterCondition),
open: savedVisible.open.filter(filterCondition),
};
const mergedVisFilesNames = {
old: [...new Set([...newVisFilesNames.old, ...otherTrackNames.old].filter(Boolean))],
new: [...new Set([...newVisFilesNames.new, ...otherTrackNames.new].filter(Boolean))],
open: [...new Set([...newVisFilesNames.open, ...otherTrackNames.open].filter(Boolean))],
};
localStorage.setItem(TRACK_VISIBLE_FLAG, JSON.stringify(mergedVisFilesNames));
// merge visible tracks with the same order (save the order of the other tracks)
const mergedVisFiles = {
old: [
...newVisFiles.old.filter(
(track) => !ctx.visibleTracks?.old.some((existing) => existing.name === track.name)
),
...(ctx.visibleTracks?.old.filter(
(track) => !newVisFiles.new.some((newTrack) => newTrack.name === track.name)
) || []),
],
new: [
...newVisFiles.new.filter(
(track) => !ctx.visibleTracks?.new.some((existing) => existing.name === track.name)
),
...(ctx.visibleTracks?.new || []),
],
};
ctx.setVisibleTracks(mergedVisFiles);
}
const processTracks = (files, savedVisible, prefix = '') => {
// ensure savedVisible is never null/undefined (e.g. first run with empty localStorage)
savedVisible = savedVisible ?? { old: [], new: [], open: [] };
// filter out empty values
Object.keys(savedVisible).forEach((key) => {
savedVisible[key] = (savedVisible[key] || []).filter(Boolean);
});
let oldFiles = [];
savedVisible.old.forEach((name) => {
const fileName = name.startsWith(prefix) ? name.slice(prefix.length) : name;
const file = files[fileName];
if (file && !file.delete) {
oldFiles.push(file);
}
});
// don't update old files, update only new ones
let newVisFiles = {
old: oldFiles,
new: [],
};
// for localStorage
let newVisFilesNames = {
old: savedVisible ? savedVisible.old : [],
new: [],
open: savedVisible ? savedVisible.open : [],
};
Object.values(files).forEach((f) => {
if (!f?.name || f?.delete) {
return;
}
const fileName = `${prefix}${f.name}`;
if (
(savedVisible.open.includes(fileName) && !isOldVisibleTrack(savedVisible, f, prefix)) ||
isNewVisibleTrack(savedVisible, f, prefix)
) {
if (isNewVisibleTrack(savedVisible, f, prefix)) {
const ind = savedVisible.new.findIndex((n) => n === fileName);
if (ind !== -1 && !newVisFiles.new[ind]) {
// If the new array at the index is empty, simply assign the current element
newVisFiles.new[ind] = f;
newVisFilesNames.new[ind] = fileName;
} else {
// Otherwise, find the next available index and assign the element
let nextFreeIndex = newVisFiles.new.findIndex((el) => !el);
if (nextFreeIndex === -1) {
// If no free indexes are found, append to the end of the array
newVisFiles.new.push(f);
newVisFilesNames.new.push(fileName);
} else {
// Assign the element to the next free index
newVisFiles.new[nextFreeIndex] = f;
newVisFilesNames.new[nextFreeIndex] = fileName;
}
}
} else {
// If it's not a new visible track, simply push the element to both arrays
newVisFiles.new.push(f);
newVisFilesNames.new.push(fileName);
}
} else {
if (isOldVisibleTrack(savedVisible, f, prefix)) {
if (savedVisible.open.includes(fileName)) {
newVisFiles.new.push(f);
newVisFilesNames.new.push(fileName);
const ind = savedVisible.old.findIndex((n) => n === fileName);
if (ind !== -1) {
savedVisible.old.splice(ind, 1);
}
}
}
}
});
return { newVisFiles, newVisFilesNames };
};
useEffect(() => {
if (ctx.openVisibleMenu?.open) {
const savedVisible = JSON.parse(localStorage.getItem(TRACK_VISIBLE_FLAG));
const newVisFilesNames = {
old: savedVisible.old || [],
new: savedVisible.new || [],
open: savedVisible.open || [],
};
localStorage.setItem(TRACK_VISIBLE_FLAG, JSON.stringify(newVisFilesNames));
} else {
if (!isEmpty(ctx.visibleTracks)) {
addCloseTracksToRecently(ctx);
}
}
}, [ctx.openVisibleMenu?.open]);
// create track groups
useEffect(() => {
if (!isEmpty(ctx.listFiles)) {
const files = getGpxFiles(ctx.listFiles);
const trackGroups = createTrackGroups({ files, ctx });
ctx.setTracksGroups(trackGroups);
} else {
const smartFolders = filterSmartFolders(ctx.tracksGroups);
ctx.setTracksGroups(smartFolders);
}
}, [ctx.listFiles, ctx.selectedSort]);
function isOldVisibleTrack(names, file, prefix = '') {
return names.old.some((n) => n === `${prefix}${file.name}`);
}
function isNewVisibleTrack(names, file, prefix = '') {
return names.new.some((n) => n === `${prefix}${file.name}`);
}
const handleCloseNotification = (event, reason) => {
if (reason === 'clickaway') return;
ctx.setNotification(null);
};
return (
<Box sx={{ display: 'flex', maxHeight: `${height}px`, overflow: 'hidden' }}>
<InstallBanner showInstallBanner={showInstallBanner} />
<HeaderMenu showInstallBanner={showInstallBanner} />
<Box
sx={{
width: { xs: `calc(100%)` },
mr: ctx.infoBlockWidth,
}}
>
<GlobalConfirmationDialog />
<OsmAndMap mainMenuWidth={MAIN_MENU_MIN_SIZE + 'px'} menuInfoWidth={MENU_INFO_SIZE} />
{ctx.globalGraph?.show && <GlobalGraph type={ctx.globalGraph.type} />}
<GlobalAlert width={width} />
<LiveShareRequests />
<Snackbar
open={!!ctx.notification}
autoHideDuration={3000}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
sx={{ mt: `${HEADER_SIZE}px` }}
onClose={handleCloseNotification}
>
<Alert severity={ctx.notification?.severity}>{ctx.notification?.text}</Alert>
</Snackbar>
<GeneralPanelButtons
mainMenuWidth={MAIN_MENU_MIN_SIZE + 'px'}
menuInfoWidth={`${TOTAL_MENU_INFO_WIDTH}px`}
showInfoBlock={showInfoBlock}
setShowInfoBlock={setShowInfoBlock}
clearState={clearState}
setMenuInfo={setMenuInfo}
showInstallBanner={showInstallBanner}
/>
{ctx.selectedPhotoInd !== -1 && <PhotosModal photos={ctx.photoGallery} />}
</Box>
<MainMenu
size={MAIN_MENU_SIZE}
infoSize={MENU_INFO_SIZE}
openMainMenu={openMainMenu}
setOpenMainMenu={setOpenMainMenu}
menuInfo={menuInfo}
setMenuInfo={setMenuInfo}
showInfoBlock={showInfoBlock}
setShowInfoBlock={setShowInfoBlock}
setClearState={setClearState}
showInstallBanner={showInstallBanner}
/>
<Dialog open={openErrorDialog} onClose={() => setOpenErrorDialog(false)}>
<DialogTitle className={dialogStyles.title}>{ctx.trackErrorMsg?.title}</DialogTitle>
<DialogContent className={dialogStyles.content}>{ctx.trackErrorMsg?.msg}</DialogContent>
<DialogActions>
<Button className={dialogStyles.button} onClick={() => ctx.setTrackErrorMsg(null)}>
Ok
</Button>
</DialogActions>
</Dialog>
</Box>
);
};
export default GlobalFrame;