-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathApp.jsx
More file actions
1429 lines (1300 loc) · 49.5 KB
/
App.jsx
File metadata and controls
1429 lines (1300 loc) · 49.5 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React from "react";
import { PLUGINS_TO_IGNORE_IN_HASH_APP_STATE } from "../constants";
import PropTypes from "prop-types";
import { styled } from "@mui/material/styles";
import Observer from "react-event-observer";
import { isMobile } from "../utils/IsMobile";
import { mapDirectionToAngle } from "../utils/mapDirectionToAngle";
import { getMergedSearchAndHashParams } from "../utils/getMergedSearchAndHashParams";
import SrShortcuts from "../components/SrShortcuts/SrShortcuts";
import Analytics from "../models/Analytics";
import AppModel from "../models/AppModel";
import {
setConfig as setCookieConfig,
functionalOk as functionalCookieOk,
} from "../models/Cookie";
import Window from "./Window";
import CookieNotice from "./CookieNotice";
import Introduction from "./Introduction/Introduction";
import Announcement from "./Announcement/Announcement";
import Alert from "./Alert";
import PluginWindows from "./PluginWindows";
import SimpleDialog from "./SimpleDialog";
import MapClickViewer from "./MapClickViewer/MapClickViewer";
import SnackbarProvider from "./SnackbarProvider";
import Search from "./Search/Search";
import CookieNoticeButton from "../controls/CookieNoticeButton";
import Zoom from "../controls/Zoom";
import User from "../controls/User";
import Rotate from "../controls/Rotate";
import ScaleLine from "../controls/ScaleLine";
import Attribution from "../controls/Attribution";
import MapCleaner from "../controls/MapCleaner";
import MapResetter from "../controls/MapResetter";
import MapSwitcher from "../controls/MapSwitcher";
import Information from "../controls/Information";
import PresetLinks from "../controls/PresetLinks";
import ExternalLinks from "../controls/ExternalLinks";
import RecentlyUsedPlugins from "../controls/RecentlyUsedPlugins";
import DrawerToggleButtons from "../components/Drawer/DrawerToggleButtons";
import { easeOut } from "ol/easing";
import {
Box,
Divider,
Drawer,
Grid,
IconButton,
Link,
Typography,
} from "@mui/material";
import LockIcon from "@mui/icons-material/Lock";
import LockOpenIcon from "@mui/icons-material/LockOpen";
import MapIcon from "@mui/icons-material/Map";
import MenuIcon from "@mui/icons-material/Menu";
import ThemeToggler from "../controls/ThemeToggler";
import HajkToolTip from "components/HajkToolTip";
// A global that holds our windows, for use see components/Window.js
document.windows = [];
const DRAWER_WIDTH = 250;
// A bunch of styled components to get the Hajk feel! Remember that some
// components are styled with the sx-prop instead/as well.
const StyledHeader = styled("header")(({ theme }) => ({
zIndex: theme.zIndex.appBar,
maxHeight: theme.spacing(8),
display: "flex",
justifyContent: "space-between",
alignItems: "flex-start",
[theme.breakpoints.down("sm")]: {
zIndex: 3,
maxHeight: theme.spacing(6),
boxShadow: theme.shadows[3],
backgroundColor: theme.palette.background.paper,
},
}));
const StyledMain = styled("main")(({ theme }) => ({
zIndex: 2,
flex: 1,
display: "flex",
paddingTop: theme.spacing(2), // we don't want the content of main box to "hit" header/footer
paddingBottom: theme.spacing(2),
[theme.breakpoints.down("sm")]: {
padding: theme.spacing(2), // on small screen the inner padding of AppBox is unset, so we must add this
},
}));
const StyledFooter = styled("footer")(({ theme }) => ({
width: "100%",
zIndex: 3,
display: "flex",
flexDirection: "row-reverse",
justifyContent: "space-between",
[theme.breakpoints.down("sm")]: {
flexDirection: "column",
},
}));
const MapContainer = styled("div")(() => ({
zIndex: 1,
position: "absolute",
left: 0,
right: 0,
bottom: 0,
top: 0,
"&:focus-visible": {
border: "2px solid black",
},
}));
const AppBox = styled("div")(({ theme }) => ({
position: "absolute",
left: 0,
right: 0,
bottom: 0,
top: 0,
padding: theme.spacing(2),
display: "flex",
flexDirection: "column",
pointerEvents: "none",
[theme.breakpoints.down("sm")]: {
padding: 0,
},
}));
const WindowsContainer = styled("div")(() => ({
position: "absolute",
left: 0,
right: 0,
bottom: 0,
top: 0,
}));
const DrawerHeaderGrid = styled(Grid)(({ theme }) => ({
padding: theme.spacing(1, 2),
backgroundColor: theme.palette.background.paper,
minHeight: theme.spacing(6),
justifyContent: "space-between",
alignItems: "center",
}));
const DrawerContentContainer = styled("div")(({ theme }) => ({
backgroundColor: theme.palette.background.paper,
height: "100%",
overflow: "auto",
}));
const FooterMapControlContainer = styled("div")(({ theme }) => ({
display: "flex",
justifyContent: "flex-end",
[theme.breakpoints.down("sm")]: {
marginBottom: theme.spacing(2),
paddingLeft: theme.spacing(2),
paddingRight: theme.spacing(2),
},
"& > *": {
marginLeft: theme.spacing(1),
},
}));
const LogoImage = styled("img")(({ theme }) => ({
height: theme.spacing(4),
}));
const DrawerTitle = styled(Typography)(({ theme }) => ({
padding: theme.spacing(1, 0),
lineHeight: 0,
}));
// TODO: The styles below are supposed to make the snackbars more usable
// on small view-ports. However, it seems the styles are not working.
// Must check with the implementer (jesade?) before migrating these.
// const styles = (theme) => {
// return {
// snackBarContainerRoot: {
// [theme.breakpoints.down("sm")]: {
// pointerEvents: "none",
// // Getting around notistack bug, can't reach snackItem.
// "& div > div > div > div": {
// pointerEvents: "auto",
// },
// },
// },
// snackbarContainerBottom: {
// [theme.breakpoints.down("sm")]: {
// bottom: "35px",
// },
// },
// snackbarContainerTop: {
// [theme.breakpoints.down("sm")]: {
// top: "18px",
// },
// },
// };
// };
/**
* The main React Component of Hajk. Rendered by index.js.
*
* @class App
* @extends {React.PureComponent}
*/
class App extends React.PureComponent {
static propTypes = {
/** List of plugins that has been activated in this instance of Hajk */
activeTools: PropTypes.array.isRequired,
/** Contains activeMap, layersConfig as well as objects that hold appConfig and mapConfig*/
config: PropTypes.object.isRequired,
};
canRenderCustomDrawer = (activeDrawerContentFromLocalStorage, tools) => {
if (
!activeDrawerContentFromLocalStorage ||
activeDrawerContentFromLocalStorage === "plugins"
) {
// If nothing was found in local storage, fall back to map config setting
activeDrawerContentFromLocalStorage =
this.props.config.mapConfig.map.activeDrawerOnStart;
}
const localStorageToolFoundInMapConfig = tools.some((tool) => {
return (
typeof activeDrawerContentFromLocalStorage === "string" &&
tool.type.toLowerCase() ===
activeDrawerContentFromLocalStorage.toLowerCase()
);
});
return (
localStorageToolFoundInMapConfig &&
activeDrawerContentFromLocalStorage &&
activeDrawerContentFromLocalStorage !== "plugins"
);
};
getDrawerPermanentFromLocalStorage = () => {
return window.localStorage.getItem("drawerPermanent") !== null
? window.localStorage.getItem("drawerPermanent") === "true"
? true
: false
: null;
};
getActiveDrawerContentFromLocalStorage = () => {
return window.localStorage.getItem("activeDrawerContent") !== null
? window.localStorage.getItem("activeDrawerContent")
: null;
};
isDrawerPermanent = (drawerProps) => {
const { props, activeDrawerContentState, drawerPermanentFromLocalStorage } =
drawerProps;
const { map } = props.config.mapConfig;
// First check if we have anything to render at all and in case we haven't -> do not show drawer
// If on a mobile device, the drawer should never be permanent.
if (activeDrawerContentState === null || isMobile) {
return false;
}
// If drawer is set to static we want the the drawer to be set to permanent
if (map.drawerStatic) {
return true;
}
// If not on mobile, if cookie is not null, use it to show/hide Drawer.
// If cookie is not null, use it to show/hide Drawer.
// If cookie however is null, fall back to the values from config.
if (drawerPermanentFromLocalStorage !== null) {
return drawerPermanentFromLocalStorage;
}
// Finally, check if drawerVisible and drawerPermanent are both true, and return true if they are.
return map.drawerVisible && map.drawerPermanent;
};
isDrawerVisible = (drawerProps) => {
const { props, activeDrawerContentState, drawerPermanentFromLocalStorage } =
drawerProps;
const { map } = props.config.mapConfig;
// First check if we have anything to render at all and in case we haven't -> do not show drawer
if (activeDrawerContentState === null) {
return false;
}
// If on a mobile device, the drawer should never be visible.
if (isMobile && map.drawerVisibleMobile !== undefined) {
return map.drawerVisibleMobile;
}
// If drawer is set to static we want the the drawer to be set to visible
if (map.drawerStatic) {
return true;
}
// If not on mobile, if cookie is not null, use it to show/hide Drawer.
// If cookie is not null, use it to show/hide Drawer.
// If cookie however is null, fall back to the values from config.
if (drawerPermanentFromLocalStorage !== null) {
return drawerPermanentFromLocalStorage;
}
// Finally, we return true if drawerVisible is set, otherwise false
return map.drawerVisible || false;
};
isDrawerStatic = (drawerProps) => {
const { drawerStatic } = drawerProps.props.config.mapConfig.map;
// We check if we have something to render or if user is on mobile.
if (drawerProps.activeDrawerContentState === null || isMobile) {
return false;
}
// And if the drawerStatic is being used at all.
if (drawerStatic !== undefined) {
return drawerStatic;
}
return drawerStatic || false;
};
constructor(props) {
super(props);
const drawerPermanentFromLocalStorage =
this.getDrawerPermanentFromLocalStorage();
const activeDrawerContentFromLocalStorage =
this.getActiveDrawerContentFromLocalStorage();
const canRenderDefaultDrawer = this.hasAnyToolbarTools();
const canRenderCustomDrawer = this.canRenderCustomDrawer(
activeDrawerContentFromLocalStorage,
props.config.mapConfig.tools
);
//Check if we have customContent to render in drawer
//if we can render customContent, use it set the drawer content.
//if we cant render customContent fall back to mapconfig
//Finally, fall back to 'plugins', the standard tools panel.
//This fall back avoids rendering an empty drawer in the case that draw is set to visible but there is no drawer content in local storage.
const activeDrawerContentState = canRenderCustomDrawer
? activeDrawerContentFromLocalStorage !== null &&
activeDrawerContentFromLocalStorage !== "plugins"
? activeDrawerContentFromLocalStorage
: this.props.config.mapConfig.map.activeDrawerOnStart
: canRenderDefaultDrawer
? "plugins"
: null;
const drawerProps = {
props,
activeDrawerContentState,
drawerPermanentFromLocalStorage,
};
// We check if drawer is set to static
const drawerStatic = this.isDrawerStatic(drawerProps);
// We check if drawer is set to permanent
// If drawerStatic is true, we do not need to check drawerPermanent
const drawerPermanent = drawerStatic
? true
: this.isDrawerPermanent(drawerProps);
// We check if drawer is set to visible
// If drawerStatic is true, we do not need to check drawerVisible
const drawerVisible = drawerStatic
? true
: this.isDrawerVisible(drawerProps);
this.state = {
alert: false,
drawerButtons: [],
loading: false,
mapClickDataResult: {},
drawerVisible: drawerVisible,
drawerPermanent: drawerPermanent,
drawerStatic: drawerStatic,
activeDrawerContent: activeDrawerContentState,
drawerMouseOverLock: false,
};
// If the drawer is set to be visible at start - ensure the activeDrawerContent
// is set to current content. If we don't allow functional cookies, we cannot do that obviously.
if (drawerVisible && drawerPermanent && activeDrawerContentState !== null) {
if (functionalCookieOk()) {
window.localStorage.setItem(
"activeDrawerContent",
activeDrawerContentState
);
}
}
this.buttonToggleDrawerPermanentRef = React.createRef();
this.globalObserver = new Observer();
// Initiate the Analytics model
props.config.mapConfig.analytics && this.initiateAnalyticsModel();
this.infoclickOptions = this.props.config.mapConfig.tools.find(
(t) => t.type === "infoclick"
)?.options;
// We have to initialize the cookie-manager so we know how cookies should be managed.
// The manager should ideally only be initialized once, since the initialization determines
// wether the cookie-notice has to be shown or not. Running setConfig() again will not lead
// to a new prompt.
setCookieConfig({
showCookieNotice: props.config.mapConfig.map.showCookieNotice,
globalObserver: this.globalObserver,
});
AppModel.init({
config: props.config,
globalObserver: this.globalObserver,
refreshMUITheme: props.refreshMUITheme,
});
this.appModel = AppModel;
}
hasAnyToolbarTools = () => {
const { config, activeTools } = this.props;
return config.mapConfig.tools.some((tool) => {
return (
tool.options.target === "toolbar" &&
activeTools
.map((activeTool) => activeTool.toLowerCase())
.includes(tool.type.toLowerCase())
);
});
};
checkConfigForUnsupportedTools = () => {
// The plugin names can be fancy, but are always lower case in mapConfig:
const lowerCaseActiveTools = this.props.activeTools.map((t) =>
t.toLowerCase()
);
// Let's push some built-in core elements, that previously were plugins
// and that still have their config there.
lowerCaseActiveTools.push("preset");
lowerCaseActiveTools.push("externallinks");
lowerCaseActiveTools.push("information");
// Check which plugins defined in mapConfig don't exist in appConfig.availableTools
const unsupportedToolsFoundInMapConfig = this.props.config.mapConfig.tools
.map((t) => t.type.toLowerCase())
.filter((e) => {
// Special case: "infoclick" will never exist in activeTools (as it's core)
// so we can assume it's supported even if it isn't found in activeTools.
if (e === "infoclick") return false;
// Check if activeTools contain the plugin supplied in this configuration.
// If not, leave it in this array.
return !lowerCaseActiveTools.includes(e);
});
// Display a silent info message in console
unsupportedToolsFoundInMapConfig.length > 0 &&
console.info(
`The map configuration contains unavailable plugins: ${unsupportedToolsFoundInMapConfig.join(
", "
)}. Please check your map config. `
);
};
/**
* @summary Initiates the wanted analytics model (if any).
* @description If Hajk is configured to track map usage, this method will
* initialize the model and subscribe to two events ("analytics.trackPageView"
* and "analytics.trackEvent").
*
* @memberof App
*/
initiateAnalyticsModel() {
this.analytics = new Analytics(
this.props.config.mapConfig.analytics,
this.globalObserver
);
}
componentDidMount() {
this.checkConfigForUnsupportedTools();
const promises = this.appModel
.createMap()
.addSearchModel()
.addLayers()
.addAnchorModel() // Anchor model must be added after the layers
.loadPlugins(this.props.activeTools);
Promise.all(promises).then(() => {
// Track the page view
this.globalObserver.publish("analytics.trackPageView");
// Track the mapLoaded event, distinguish between regular and
// cleanMode loads. See #1077.
this.globalObserver.publish("analytics.trackEvent", {
eventName: "mapLoaded",
activeMap: this.props.config.activeMap,
cleanMode: this.props.config.mapConfig.map.clean,
});
// Determine the icon based on the config value
const drawerButtonIcon =
this.props.config.mapConfig.map?.drawerButtonIcon;
// Mapping object for icons
const iconMapping = {
MapIcon: MapIcon,
MenuIcon: MenuIcon,
};
// Return the mapped icon or a default one if not found
const ButtonIcon = iconMapping[drawerButtonIcon] || MapIcon;
this.setState(
{
tools: this.appModel.getPlugins(),
},
() => {
// If there's at least one plugin that renders in the Drawer Map Tools List,
// tell the Drawer to add a toggle button for the map tools
this.appModel.getPluginsThatMightRenderInDrawer().length > 0 &&
this.globalObserver.publish("core.addDrawerToggleButton", {
value: "plugins",
ButtonIcon: ButtonIcon,
caption:
this.props.config.mapConfig.map?.drawerButtonTitle ??
"Kartverktyg",
drawerTitle:
this.props.config.mapConfig.map?.drawerTitle ?? "Kartverktyg",
order: 0,
// If no plugins render **directly** in Drawer, but some **might**
// render there occasionally, let's ensure to hide the Tools button on
// medium screens and above.
hideOnMdScreensAndAbove:
this.appModel.getDrawerPlugins().length === 0 &&
this.appModel.getPluginsThatMightRenderInDrawer().length > 0,
renderDrawerContent: function () {
return null; // Nothing specific should be rendered - this is a special case!
},
});
// Ensure to update the map canvas size. Otherwise we can run into #1058.
this.appModel.getMap().updateSize();
// Tell everyone that we're done loading (in case someone listens)
this.globalObserver.publish("core.appLoaded");
}
);
});
this.bindHandlers();
}
componentDidCatch(error) {}
bindHandlers() {
// Extend the hajkPublicApi with a couple of things that are available now
window.hajkPublicApi = {
...window.hajkPublicApi,
olMap: this.appModel.map,
dirtyLayers: {},
};
// Register a handle to prevent pinch zoom on mobile devices.
document.body.addEventListener(
"touchmove",
(event) => {
// If this event would result in changing scale …
// scale is always undefined on Android so we need to handle it, otherwise we loose the ability to scroll.
// For the prevention pinch-zoom on Android. Check index.css
if (event.scale !== undefined && event.scale !== 1) {
// …cancel it.
event.preventDefault();
}
// Else, allow all non-scale-changing touch events, e.g.
// we still want scroll to work.
},
{ passive: false } // Explicitly tell the browser that we will preventDefault inside this handler,
// which is important for smooth scrolling to work correctly.
);
// Some tools (such as those that use the DrawModel) will tell
// the Public API if user has made any changes that would be lost
// on a window close/reload. We listen to the appropriate event
// and check with the "dirtyLayers" object in order to determine
// whether to show the confirmation dialog. See #1403.
this.appModel.config.mapConfig.map.confirmOnWindowClose !== false &&
window.addEventListener("beforeunload", function (event) {
if (Object.keys(window.hajkPublicApi.dirtyLayers).length > 0) {
event.preventDefault();
return (event.returnValue = "");
}
});
// This event is used to allow controlling Hajk programmatically, e.g in an embedded context, see #1252
this.props.config.mapConfig.map.enableAppStateInHash === true &&
window.addEventListener(
"hashchange",
() => {
// Extract existing params. Using this helper we will take into account both
// the query and the hash parameters.
const mergedParams = getMergedSearchAndHashParams();
// If map changed, do a full reload
if (mergedParams.get("m") !== this.props.config.activeMap) {
window.location.reload();
}
// Act when view's zoom changes
if (mergedParams.get("z")) {
// Since we're dealing with a string, we have to parse it to a float.
// We must also round it to the nearest integer in order to avoid bouncing in View:
// View's getZoom() returns a float, but our hash param is always an integer.
// See also: #1422.
const zoomInHash = Math.round(parseFloat(mergedParams.get("z")));
if (
Math.round(this.appModel.map.getView().getZoom()) !== zoomInHash
) {
// …let's update our View's zoom.
this.appModel.map.getView().animate({ zoom: zoomInHash });
}
}
// Act when view's center coordinate changes
if (mergedParams.get("x") || mergedParams.get("y")) {
const [x, y] = this.appModel.map.getView().getCenter();
if (
mergedParams.get("x") !== x.toString() ||
mergedParams.get("y") !== y.toString()
) {
this.appModel.map.getView().animate({
center: [mergedParams.get("x"), mergedParams.get("y")].map(
(coord) => coord * 1.0
),
});
}
}
// Act when plugin window's visibility changes.
// p contains the list of plugins to show. It's important to check
// for null, as an empty string value is a valid value that indicates
// that no plugin should be shown, while a null value indicates that
// the parameter does not exist and default plugin visibility should
// be respected.
if (mergedParams.get("p") !== null) {
const currentlyVisiblePlugins = this.appModel.windows
.filter((w) => w.state.windowVisible)
.map((p) => p.type);
if (currentlyVisiblePlugins.join(",") !== mergedParams.get("p")) {
const pInParams = mergedParams.get("p").split(",");
// First hide if window not longer visible
currentlyVisiblePlugins.forEach((p) => {
if (
!pInParams.includes(p) &&
PLUGINS_TO_IGNORE_IN_HASH_APP_STATE.indexOf(p) === -1
) {
this.globalObserver.publish(`${p}.closeWindow`);
}
});
// Next, show any windows that are still hidden
mergedParams
.get("p")
.split(",")
.forEach((p) => {
PLUGINS_TO_IGNORE_IN_HASH_APP_STATE.indexOf(p) === -1 &&
this.globalObserver.publish(`${p}.showWindow`);
});
}
}
// Act when search string changes.
// Check if the q parameter exists and differs from
// the most recent search. If so, let's publish an event that
// the Search component listens to.
// TODO: Also handle sources change, the s parameter
if (
mergedParams.get("q") !==
this.appModel.searchModel.lastSearchPhrase &&
mergedParams.get("q") !== null
) {
this.globalObserver.publish(
"search.setSearchPhrase",
mergedParams.get("q")
);
}
// Act when the l parameter changes
if (mergedParams.get("l") || mergedParams.get("gl")) {
this.appModel.setLayerVisibilityFromParams(
mergedParams.get("l"),
mergedParams.get("gl")
);
}
},
false
);
// Register various global listeners.
this.globalObserver.subscribe("infoClick.mapClick", (results) => {
this.setState({
mapClickDataResult: results,
});
});
this.globalObserver.subscribe("core.alert", (message) => {
this.setState({
alert: true,
alertMessage: message,
});
});
this.globalObserver.subscribe("core.hideDrawer", () => {
// If Drawer is currently permanent,
// flip the permanent toggle. Please note that
// this will do some fixes, flip the state value
// and, finally, invoke this function (core.hideDrawer) again
// (but with new value for drawerPermanent this time!).
if (this.state.drawerPermanent) {
this.togglePermanent();
} else {
this.setState({ drawerVisible: false });
// Also, tell the Drawer Buttons Component to unset active button
this.globalObserver.publish("core.unsetActiveButton");
}
});
this.globalObserver.subscribe("core.onlyHideDrawerIfNeeded", () => {
// Invoked when user clicks any of the Plugin buttons in Drawer,
// this is needed as we don't want to toggle the Drawer in this
// case, but only hide it IF it's not permanent.
// This differs from the "normal" hideDrawer event, that will
// ensure that Drawer is hidden - no matter the permanent state -
// as it will first flip the drawerPermanent value (if needed), prior
// to closing.
if (this.state.drawerPermanent === false) {
this.setState({ drawerVisible: false });
// Also, tell the Drawer Buttons Component to unset active button
this.globalObserver.publish("core.unsetActiveButton");
}
});
this.globalObserver.subscribe("core.drawerContentChanged", (v) => {
if (v !== null) {
this.setState({ drawerVisible: true, activeDrawerContent: v });
} else {
if (!this.state.drawerStatic) {
this.globalObserver.publish("core.hideDrawer");
}
}
});
this.globalObserver.subscribe("core.addDrawerToggleButton", (button) => {
this.setState((prevState) => ({
drawerButtons: [...prevState.drawerButtons, button],
}));
this.globalObserver.subscribe("core.drawerToggled", () => {
if (this.state.drawerPermanent) {
if (this.buttonToggleDrawerPermanentRef) {
this.buttonToggleDrawerPermanentRef.focus();
}
}
});
});
/**
* TODO: Implement correctly a way to remove features from map click
* results when layer visibility is changed. The current implementation
* has problems with group layers: if we have a group layer and toggle
* its visibility, the features are not removed from infoclick window.
*/
// this.appModel
// .getMap()
// .getLayers()
// .getArray()
// .forEach((layer) => {
// layer.on("change:visible", (e) => {
// const layer = e.target;
// if (Array.isArray(this.state.mapClickDataResult.features)) {
// this.state.mapClickDataResult.features.forEach((feature) => {
// if (feature.layer === layer) {
// const o = { ...this.state.mapClickDataResult };
// o.features = o.features.filter((f) => f !== feature);
// this.setState({
// mapClickDataResult: o,
// });
// }
// });
// }
// });
// });
// Add some listeners to each layer's change event
this.appModel
.getMap()
.getLayers()
.getArray()
.forEach((layer) => {
layer.on("change:visible", (e) => {
const olLayer = e.target;
// If the Analytics object exists, let's track layer visibility
if (this.analytics && olLayer.get("visible") === true) {
const opts = {
eventName: "layerShown",
activeMap: this.props.config.activeMap,
layerId: olLayer.get("name"),
layerName: olLayer.get("caption"),
};
// Send a custom event to the Analytics model
this.globalObserver.publish("analytics.trackEvent", opts);
}
// If a base layer becomes visible, set the map rotation to match.
// When this runs the OpenStreetMap layer (if enable) don't exist
// yet. As a workaround this code is duplicated in:
// `plugins/LayerSwitcher/components/BackgroundSwitcher.js`
if (olLayer.get("visible") && olLayer.get("layerType") === "base") {
const map = this.appModel.getMap();
const direction = olLayer.get("rotateMap");
const duration = 1000;
const angle = mapDirectionToAngle(direction);
map.getView().animate({
rotation: angle,
duration: duration,
easing: easeOut,
});
}
// Not related to Analytics: send an event on the global observer
// to anyone wanting to act on layer visibility change.
this.globalObserver.publish("core.layerVisibilityChanged", e);
});
// Listener for "quickAccess" changes
layer.on("change:quickAccess", (e) => {
// Send an event on the global observer
// to anyone wanting to act on layer quickAccess change.
this.globalObserver.publish("core.layerQuickAccessChanged", e);
});
// Listener for "subLayers" changes
layer.on("change:subLayers", (e) => {
// Send an event on the global observer
// to anyone wanting to act on layer subLayers change.
this.globalObserver.publish("core.layerSubLayersChanged", e);
});
});
}
renderInfoclickWindow() {
// Check if admin wants Infoclick to be active
const { infoclickOptions } = this;
// The 'open' prop, below, will control whether the Window is
// currently visible or not. The 'open' property itself
// depends on whether there are Features to display or not.
//
// That, in turn, depends on what's in the current state of 'mapClickDataResult'.
//
// It will be changed each time user clicks on map (as we have it registered
// like that in Click.js), so we can be confident that __after each user
// click we do have the most current results in our state__.
//
// Note however that which layers are included is controlled by
// __layer visibility at the time the click event happens!__
//
// As soon as user starts to show/hide layers __after__ the click, our
// 'mapClickDataResult' may contain results from hidden layers (or not
// contain results from layers activated after the click occurred).
//
// This may or may not be a bug (depending on how we see it), and may
// be fixed in the future.
return (
infoclickOptions !== undefined && (
<Window
open={this.state.mapClickDataResult?.features?.length > 0} // Will show window only if there are any features to show
globalObserver={this.globalObserver}
title={infoclickOptions.title || "Infoclick"}
position={infoclickOptions.position || "right"}
mode="window"
width={infoclickOptions.width || 400}
height={infoclickOptions.height || 300}
features={this.state.mapClickDataResult?.features}
options={
this.appModel.config.mapConfig.tools.find(
(t) => t.type === "infoclick"
)?.options
}
map={this.appModel.getMap()}
onDisplay={(feature) => {
this.appModel.highlight(feature);
}}
onClose={() => {
this.appModel.highlight(false);
this.setState({
mapClickDataResult: undefined,
});
}}
/>
)
);
}
/**
* Flip the @this.state.drawerPermanent switch, then perform some
* more work to ensure the OpenLayers canvas has the correct
* canvas size.
*
* @memberof App
*/
togglePermanent = (e) => {
this.setState({ drawerPermanent: !this.state.drawerPermanent }, () => {
// Viewport size has changed, hence we must tell OL
// to refresh canvas size.
this.appModel.getMap().updateSize();
// If Drawer has been "(un)permanented", our #windows-container size has changed.
// To ensure that our Windows still are inside the container, we dispach an
// event that all Windows subscribe to.
this.globalObserver.publish("core.drawerToggled");
// If we allow functional cookies, let's save the current state of drawerPermanent
// to LocalStorage, so that the application can reload to the same state.
if (functionalCookieOk()) {
window.localStorage.setItem(
"drawerPermanent",
this.state.drawerPermanent
);
}
// If user clicked on Toggle Permanent and the result is,
// that this.state.drawerPermanent===false, this means that we
// have exited the permanent mode. In this case, we also
// want to ensure that Drawer is hidden (otherwise we would
// just "un-permanent" the Drawer, but it would still be visible).
this.state.drawerPermanent === false &&
this.globalObserver.publish("core.hideDrawer");
// Publish the event to notify plugins to re-render
this.globalObserver.publish("core.pluginsRerender");
});
};
handleMouseEnter = (e) => {
this.setState({ drawerMouseOverLock: true });
};
handleMouseLeave = (e) => {
this.setState({ drawerMouseOverLock: false });
};
renderSearchComponent() {
// FIXME: We should get the search config from somewhere else (not from plugin options) now when Search is part of Core...
if (
this.appModel.plugins.search &&
this.appModel.plugins.search.options.renderElsewhere !== true
) {
return (
<Search
map={this.appModel.getMap()}
app={this}
options={this.appModel.plugins.search.options}
/>
);
} else {
return null;
}
}
renderInformationPlugin() {
const c = this.appModel.config.mapConfig.tools.find(
(t) => t.type === "information"
);
return (
c !== undefined &&
c.hasOwnProperty("options") && <Information options={c.options} />
);
}
isString(s) {
return s instanceof String || typeof s === "string";
}
drawerIsLocked() {
const { config } = this.props;
const clean = config.mapConfig.map.clean;
// The user might have locked the drawer while in regular mode,
// hence we must make sure we're not in clean mode, because
// if we are, the drawer cannot be locked, and we should return false.
return this.state.drawerPermanent && clean === false;